c programming with solutions

227
C Programming Turbo C Programming Using Turbo C++ Compiler Turbo C - Data Types 1.Turbo c struct: Source Code: struct MyClass { int m; int a; int b; double d; char dname[24]; }; Output None 2. Turbo c struct and union: struct MyStruct { long lValue; char ch; char buf[4]; float f; }; union MyUnion { long lValue; char ch;

Upload: victor-othugadi

Post on 29-Nov-2014

236 views

Category:

Documents


4 download

DESCRIPTION

for beginners(freshers)

TRANSCRIPT

Page 1: C Programming With Solutions

C Programming

Turbo C Programming Using Turbo C++ Compiler

Turbo C - Data Types

1.Turbo c struct:

Source Code:

struct MyClass{    int m;  int a; int b; double d; char dname[24];};

Output

None

2. Turbo c struct and union:

struct MyStruct

{

long lValue;

char ch;

char buf[4];

float f;

};

 

union MyUnion

{

long lValue;

char ch;

char buf[4];

float f;

};

Page 2: C Programming With Solutions

3.ENUMERATORS:

void main(){   enum Location {        LocUSA, LocUK, LocGermany, LocIndia, LocChina, LocJapan,          LocPhilippines, LocMalaysia, LocSingapore, LocThailand,          LocIndonesia, LocOthers    };     enum Random {        randData1 = -23, randData2, randData3, randData4 = 10, randData5    };     printf("USA: %d\n", LocUSA);    printf("India: %d\n", LocIndia);    printf("randData2: %d\n", randData2);     printf("randData5: %d\n", randData5);} 

Output

USA: 0

India: 3

randData2: -22

randData5: 11

 

Press any key to continue . . .

4.double array initialization and counting the number of elements

Source Code

#include <stdio.h>#include <stdlib.h>#include <conio.h>#include <bios.h>#include <ctype.h> static double numbers[] ={        10.11, 10.12, 10.13, 10.14}; void main(){

Page 3: C Programming With Solutions

        int numElements = sizeof(numbers) / sizeof(numbers[0]);        for(int i = 0; i <numElements; i++)                printf("%d\n", numbers[i]);}

Output

10.1110.1210.1310.14

5. STRING ARRAY INTILIZATION:

Source Code

 #include <stdio.h>#include <stdlib.h>#include <conio.h>#include <bios.h>#include <ctype.h>  static char *arrayCountryNames[] = {      "USA", "UK", "India", "Dubai", "Singapore", "Australia",      "Malaysia", "Phillipines", "Manila", "Ethopia", "Canada"}; void main(){      int numElements = sizeof(arrayCountryNames) / sizeof(arrayCountryNames[0]);    int i = 0;      for(i = 0; i <numElements; i++)            printf("%s\n", arrayCountryNames[i]);}

Output

USA UK India Dubai Singapore Australia Malaysia Phillipines Manila Ethopia Canada

Page 4: C Programming With Solutions

6. Retriving string array from a function

Source Code

#include <stdio.h>#include <stdlib.h>#include <conio.h>#include <bios.h>#include <ctype.h>  void GetCountryNames(char ***p, int *n){      static char *arrayCountryNames[] = {            "USA", "UK", "India", "Dubai", "Singapore", "Australia",            "Malaysia", "Phillipines", "Manila", "Ethopia", "Canada"      };       *p =  arrayCountryNames;      *n = sizeof(arrayCountryNames) / sizeof(arrayCountryNames[0]); }; void main(){       int numElements = 0;      char **p = 0;       GetCountryNames(&p, &numElements);       for(int i = 0; i < numElements; i++)            printf("%s\n", p[i]); }

Output

USA UK India Dubai Singapore Australia Malaysia Phillipines Manila Ethopia Canada

7. Const and Non Const Variables

Source Code

Page 5: C Programming With Solutions

 #include <stdio.h>#include <stdlib.h>#include <conio.h>#include <bios.h>#include <string.h> void main(){       const char *p1 = "victor";      char *p2 = "victor";      const char * const p3 = "victor";      char * const p4 = "victor";       p1 = 0;      p2 = 0;      //p3 = 0; // Compilation Error      //p4 = 0; // Compilation Error       // strcpy(p1, "victor"); // Compilation Error      strcpy(p2, "victor"); // Compilation Error      // strcpy(p3, "victor"); // Compilation Error      strcpy(p4, "victor"); // Compilation Error // p1 - content can not be changed, but ptr can be changed// p2 - both content and ptr can be changed// p3 - Neither content not ptr can be changed// p4 - ptr can not be changed but content can be changed }

Output

None

8. Switch Case Statement

Source Code

int main(){    enum Location {        LocUSA, LocUK, LocGermany, LocIndia, LocChina, LocJapan,        LocPhilippines, LocMalaysia, LocSingapore, LocThailand,        LocIndonesia, LocOthers    };     Location key = LocIndia;     switch(key)    {    case LocUSA:        {            printf("USA");

Page 6: C Programming With Solutions

            break;        }    case LocUK:        {            printf("UK");            break;        }    case LocGermany:        {            printf("Germany");            break;        }    case LocIndia:        {            printf("India");            break;        }    case LocChina:        {            printf("China");            break;        }    case LocPhilippines:        {            printf("Philippines");            break;        }    default:        {            printf("Others");            break;        }    };}

Output

India

9. Static Global Variables

Source Code

#include <stdio.h>

 static int IsEntered = -1; void DisplayStatus(){    if(IsEntered == 1)        printf("Function Enters\n");    else if(IsEntered == 2)        printf("Function Exits\n");    else        printf("Not initialized\n");

Page 7: C Programming With Solutions

} void EnterFunction(){    IsEntered = 1;} void ExitFunction(){    IsEntered = 2;} int main(){    DisplayStatus();    EnterFunction();    DisplayStatus();    ExitFunction();    DisplayStatus();     return 0;}

Output

Not initializedFunction EntersFunction Exits

10. Static Variables

Source Code

#include <stdio.h>

static char msg[] = "Welcome to my static function\n";

void DisplayWelcomeMessage(){       printf(msg); // Accessing the msg static variable in sub function in the current file}

int main(){    // Accessing the msg static variable in main function in the current file    printf(msg);    DisplayWelcomeMessage();}

Output

Welcome to my static functionWelcome to my static function

Page 8: C Programming With Solutions

11. Static Functions

Source Code

#include <stdio.h>

static const char* GetWelcomeMessage(){

        static char msg[] = "Welcome to my static function\n";        return msg;}

int main(){    // GetWelcomeMessage can only be accessed in the current .CPP file    printf(GetWelcomeMessage());// It will display Welcome to my static function as output}

Output

Welcome to my static function

12. Use of #define macro

Source Code

#define MAX_ELEMENTS 10 int _tmain(int argc, TCHAR* argv[]){    int arrayData[MAX_ELEMENTS];    int CloneData[MAX_ELEMENTS];     for(int i = 0; i < MAX_ELEMENTS; i++)    {        scanf("%d", &arrayData[i]);    }     for(int i = 0; i < MAX_ELEMENTS; i++)    {        CloneData[i] = arrayData[i];    }     for(int i = 0; i < MAX_ELEMENTS; i++)    {        printf("%d\n", CloneData[i]);    }     int a = 10 + 20 + 30;    int b = a; 

Page 9: C Programming With Solutions

    return 0;}

Output

102030405060708090100102030405060708090100

LOOPS AND LOGICAL CONDITIONS:1.Armstrong Numbers

Source Code

 

#include <stdio.h>

 

int main()

{

      int i, a, b, c, d;

      printf("List of Armstrong Numbers between (100 - 999):\n");

 

      for(i = 100; i <= 999; i++)

      {

            a = i / 100;

            b = (i - a * 100) / 10;

            c = (i - a * 100 - b * 10);

 

            d = a*a*a + b*b*b + c*c*c;

 

            if(i == d)

Page 10: C Programming With Solutions

            {

                  printf("%d\n", i);

            }

      }  

      return 0;

}   

Output

 List of Armstrong Numbers between (100 - 999):153370371407 

2. Fibonacci Series

Source Code

 

// Program for Fibonacci Number

 

#include <stdio.h>

 

void main()

{

      int f1 = 0, f2 = 1, f3, n;

      printf("Program for Fibonacci Series\n");

      printf("Enter the maximum number for Fibonacci Series: ");

      scanf("%d", &n);

      printf("\nPrinting Fibonacci Series from 0 - %d\n", n);

      printf("%d\n%d\n", f1, f2);

      while(1)

      {

            f3 = f1 + f2;

            if(f3 > n)

                  break;

            printf("%d\n", f3);

            f1 = f2;

            f2 = f3;

Page 11: C Programming With Solutions

      }

Output

 Program for Fibonacci SeriesEnter the maximum number for Fibonacci Series: Printing Fibonacci Series from 0 - 100001123581321345589144233377610987  

3.  Loops - display numbers using for loop, while loop and do while loop

Source Code

#include <stdio.h> int main(){     int num = 0;    printf("Using while loop\n");    while(1)    {        num = num + 1;printf("%d\n", num);        if(num >= 5)            break;    }     printf("Using do while loop\n");     num = 0;    do    {

Page 12: C Programming With Solutions

        num = num + 1;        printf("%d\n", num);} while(num < 5);     printf("Using for loop\n");     for(num = 1; num <= 5; num++)    {printf("%d\n", num);    };     return 0;   }

Output

Using while loop12345Using do while loop12345Using for loop12345Press any key to continue . . .

5. Creating Pyramid using loops

Source Code

#include <stdio.h>

 int main(){    int i,j,k, n;    printf("Enter number of rows for pyramid: ");    scanf("%d", &n);     printf("\n");     for(i = 1; i <= n; i++)    {

Page 13: C Programming With Solutions

        for(j = 0; j < (n - i); j++)            printf(" ");        for(j = 1; j <= i; j++)            printf("*");        for(k = 1; k < i; k++)            printf("*");        printf("\n");    }    printf("\n\n");     return 0;}

Output

Enter number of rows pyramid: 21                     *                   ***                  *****                 *******                *********               ***********              *************             ***************            *****************           *******************

Page 14: C Programming With Solutions

          *********************         ***********************        *************************       ***************************      *****************************     *******************************    *********************************   ***********************************  ************************************* ********************************************************************************

6. Loops - Read Numbers and Check Odd or Even Number

Source Code

#include <stdio.h>

int main()

{    printf("Program to find ODD or Even Number\n");    while(1)    {        int n = 0;        printf("\nEnter a number(-1 for Exit): ");        scanf("%d",&n);         if( n == -1)            break;         if((n % 2) == 0)        {            printf("%d is a EVEN number.\n", n);        }        else        {            printf("%d is a ODD number.\n", n);        }    }    return 0;}

Output

Program to find ODD or Even Number Enter a number(-1 for Exit): 11 is a ODD number. Enter a number(-1 for Exit): 2

Page 15: C Programming With Solutions

2 is a EVEN number. Enter a number(-1 for Exit): 33 is a ODD number. Enter a number(-1 for Exit): 44 is a EVEN number. Enter a number(-1 for Exit): 55 is a ODD number. Enter a number(-1 for Exit): 66 is a EVEN number. Enter a number(-1 for Exit): 77 is a ODD number. Enter a number(-1 for Exit): -1 Press any key to continue . . . 

7.Loops - for loop, while loop and do while loop

Source Code

bool CopyFile2(const char *srcFileName, const char *destFileName){

     FILE *istream = fopen(srcFileName, "rb");    FILE *ostream = fopen(destFileName, "wb");    if (istream == 0 || ostream == 0)        return false;    const int len = 4096;    char buf[4096];     //////////////////////////////////////////////////////    while(1)    {        if( feof(istream))            break;        int nBytesRead = fread(buf, 1, len, istream);        if(nBytesRead <= 0)            break;        fwrite(buf, 1, nBytesRead, ostream);    }    //////////////////////////////////////////////////////     //////////////////////////////////////////////////////    for(;;)    {        if( feof(istream))

Page 16: C Programming With Solutions

            break;        int nBytesRead = fread(buf, 1, len, istream);        if(nBytesRead <= 0)            break;        fwrite(buf, 1, nBytesRead, ostream);    }    //////////////////////////////////////////////////////

     //////////////////////////////////////////////////////    do    {        if( feof(istream))            break;        int nBytesRead = fread(buf, 1, len, istream);        if(nBytesRead <= 0)            break;        fwrite(buf, 1, nBytesRead, ostream);    } while(1);    //////////////////////////////////////////////////////

     fclose(istream);    fclose(ostream);    return true;

}

Output

None 

8. Reverse a String With Out Using String Library Functions

Source Code

bool ReverseString(const char *src, char *dst, int len){    const char *p = src;     // count the length    int count = 0;    int i = 0, j = 0, k = 0;    while(1)    {        if(p == NULL || *p == '\0' ||            *p == '\t' || *p =='\n' || *p == '\r')        {            count = i;            break;        }

Page 17: C Programming With Solutions

        p = p + 1;        i = i + 1;    }     if(count > len)    {        return false; // Insufficient memory in the destination pointer    }     for(j = count - 1; j >= 0; j--)    {        dst[k++] = src[j];    }    dst[k] = '\0';     return true;} 

 int main(){     char src[] = "victor";    char dst[32];    ReverseString(src, dst, 32);    printf("%s\n%s\n", src, dst );    return 0;}

Output

victorrotciv

9.Loops - Build Pattern of * and numbers using loops

Source Code

#include <stdio.h> int main(){    int i,j,n;    printf("Enter a number: ");    scanf("%d", &n);     printf("\n");     for(i = n; i > 1; i--)    {        for(j = 1; j <= i; j++)

Page 18: C Programming With Solutions

            printf("*");        printf("\n");    }    for(i = 1; i <= n; i++)    {        for(j = 1; j <= i; j++)            printf("*");        printf("\n");    }    printf("\n");     for(i = 1; i < n; i++)    {        for(j = 1; j <= i; j++)            printf("%d",j);        printf("\n");    }    for(int i = n; i >= 0; i--)    {        for(int j = 1; j <= i; j++)            printf("%d",j);        printf("\n");    }    printf("\n");     return 0;}

Output

Enter a number: 6 ***************************************** 112123

Page 19: C Programming With Solutions

123412345123456123451234123121

10. Convert Numbers to Text (Words)

Source Code

#include <stdio.h>#include <string.h>  bool HelperConvertNumberToText(int num, char *buf, int len){    static char *strones[] = {      "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight",      "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen",      "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen",    };     static char *strtens[] = {        "Ten", "Twenty", "Thirty", "Fourty", "Fifty", "Sixty",        "Seventy", "Eighty", "Ninety", "Hundred"    };

    char result[1024];     int single, tens, hundreds;     if(num > 1000)        return false;     hundreds = num / 100;    num = num - hundreds * 100;    if( num < 20)    {        tens = 0; // special case        single = num;    }    else    {        tens = num / 10;        num = num - tens * 10;        single = num;    }     memset(result, 0, 1024);       if(hundreds > 0)    {        strcat(result, strones[hundreds-1]);        strcat(result, " Hundred ");

Page 20: C Programming With Solutions

    }    if(tens > 0)    {        strcat(result, strtens[tens-1]);        strcat(result, " ");    }    if(single > 0)    {        strcat(result, strones[single-1]);        strcat(result, " ");    }     if(len > strlen(result))        strcpy(buf, result);     return true;} bool ConvertNumberToText(int num, char *buf, int len){    char tres[1024];    char result[1024];    int thousands;    int temp;    if(num < 0 || num > 100000)    {        printf( " %d \t Not Supported\n", num);        return false;    }     if( num == 0)    {        printf(" %d \t Zero\n", num);        return false;    }     memset(result, 0, 1024);     if(num < 1000)    {          HelperConvertNumberToText(num, (char*) &tres, 1024);        strcat(result, tres);    }    else    {        thousands = num / 1000;        temp = num - thousands * 1000;         HelperConvertNumberToText(thousands, (char*) &tres, 1024);        strcat(result, tres);        strcat(result, "Thousand ");        HelperConvertNumberToText(temp, (char*) &tres, 1024);        strcat(result, tres);    }       if(len > strlen(result))        strcpy(buf, result);

Page 21: C Programming With Solutions

    return true;} int main(){    int len = 1024;    char result[1024];    int  i, num;    static int arrNum[] =    {      -1, 0, 5, 10, 15, 19, 20, 21, 25, 33, 49, 50, 72,      99, 100, 101, 117, 199, 200, 214, 517, 589, 999,      1000, 1010, 1018, 1200, 9890, 10119, 13535, 57019,      99999, 100000, 100001    };     for(i = 0; i < sizeof(arrNum) / sizeof(int); i++)    {        num = arrNum[i];        if( ConvertNumberToText(num, result, len) == true)            printf("%d \t %d\n", num, result);    }    return 0;}

 

Output

-1       Not Supported0        Zero5        Five10       Ten15       Fifteen19       Nineteen20       Twenty21       Twenty One25       Twenty Five33       Thirty Three49       Fourty Nine50       Fifty72       Seventy Two99       Ninety Nine100      One Hundred101      One Hundred One117      One Hundred Seventeen199      One Hundred Ninety Nine200      Two Hundred214      Two Hundred Fourteen517      Five Hundred Seventeen589      Five Hundred Eighty Nine999      Nine Hundred Ninety Nine1000     One Thousand1010     One Thousand Ten

Page 22: C Programming With Solutions

1018     One Thousand Eighteen1200     One Thousand Two Hundred9890     Nine Thousand Eight Hundred Ninety10119    Ten Thousand One Hundred Nineteen13535    Thirteen Thousand Five Hundred Thirty Five57019    Fifty Seven Thousand Nineteen99999    Ninety Nine Thousand Nine Hundred Ninety Nine100000   One Hundred Thousand100001   Not Supported

11. String to Number Conversion Program

Source Code

#include <stdio.h>#include <string.h> int StringToNumber(const char *buffer){   int result = 0;   int startIndex = 0;   int negativeNumber = 0;   int i, digit;    if(buffer[0] == '-')   {         negativeNumber = 1;         startIndex = 1;   }   for(i = startIndex; i < strlen(buffer); i++)   {      if(buffer[i] >= '0' && buffer[i] <= '9')      {         digit = buffer[i] - '0';         result = result * 10 + digit;      }      else         return 0;   }   if(negativeNumber == 1)      result *= -1;   return result;}  int main(){   char buffer[128];   int number = -1;     printf("String to Number Conversion Program\n");    while(1)   {      printf("Enter a String (-1 to exit): ");

Page 23: C Programming With Solutions

      scanf("%s", buffer);           number = StringToNumber(buffer);      printf("Converted Number: %d\n", number);       if(number == -1)         break;   }      return 0;}

Output

Example String: 5647Result Value1st Iteration: 52nd Iteration: 5 * 10 + 6 = 563rd Iteration: 56 * 10 + 5 = 5644th Iteration: 564 * 10 + 7 = 5647

12. Build Diamond Pattern of *

Source Code

#include <stdio.h>#include <conio.h>#include <process.h>#include <string.h>  void main(){    int i, j, k;    int n = 0;    printf("Program for displaying pattern of *.\n");    printf("Enter the maximum number of *: ");    scanf("%d", &n);     printf("\nHere is the Diamond of Stars\n");

Page 24: C Programming With Solutions

     for (i = 1; i <= n; i++)    {          for (j = 0; j < (n - i); j++)                printf(" ");          for (j = 1; j <= i; j++)                printf("*");          for (k = 1; k < i; k++)                printf("*");          printf("\n");    }     for (i = n - 1; i >= 1; i--)    {          for (j = 0; j < (n - i); j++)                printf(" ");          for (j = 1; j <= i; j++)                printf("*");          for (k = 1; k < i; k++)                printf("*");          printf("\n");    }       printf("\n");}

Output

13Left and Right Aligned Pattern

Source Code

Page 25: C Programming With Solutions

#include <stdio.h>#include <conio.h>#include <process.h>#include <string.h>  void main(){    int i, j, k;    int n = 0;    printf("Program for displaying pattern of *.\n");    printf("Enter the maximum number of *: ");    scanf("%d", &n);     printf("\nPattern 1 - Left Aligned:\n");     for (i = 1; i <= n; i++)    {          for (j = 1; j <= i; j++)                printf("*");          printf("\n");      }     printf("\nPattern 2 - Right Aligned:\n");     for (i = n; i >= 1; i--)    {          for(j = 0; j < n - i; j++)                printf(" ");          for (j = 1; j <= i; j++)                printf("*");          printf("\n");    }    printf("\n");}

Output

Program for displaying pattern of *.Enter the maximum number of *: 9 Pattern 1 - Left Aligned: ************************************

Page 26: C Programming With Solutions

********* Pattern 2 - Right Aligned: ********* ********  *******   ******    *****     ****      ***       **        * Press any key to continue . . . 

14. Guess Number in 5 attempts

Source Code

#include <stdio.h>#include <math.h>#include <conio.h>#include <process.h>#include <string.h>  void main(){    int i, n, diff;    int x = rand() % 100;    int bMoveHigher = 0;    int bGuessedCorrectly = 0;     printf("Welcome to Guess a Word Program\n");       for (i = 1; i <= 5; i++)    {          printf("ATTEMPT %d: Enter the your number: ", i);          scanf("%d", &n);

Page 27: C Programming With Solutions

          if (n == x)          {                printf("Congrats! You have guessed the number correctly\n");                bGuessedCorrectly = 1;                break;          }          diff = (int)(fabs(x - n));          if(x > n)                bMoveHigher = 1;          if(diff >= 50)          {                if (bMoveHigher == 0)                      printf("Your guess is VERY HIGH\n");                else                      printf("Your guess is VERY LOW\n");          }          else if (diff >= 30)          {                if (bMoveHigher == 0)                      printf("Your guess is HIGH\n");                else                      printf("Your guess is LOW\n");          }          else if (diff >= 15)          {                if (bMoveHigher == 0)                      printf("Your guess is MODERATELY HIGH\n");                else                      printf("Your guess is MODERATELY LOW\n");          }          else          {                if (bMoveHigher == 0)                      printf("Your guess is SOMEWHAT HIGH\n");                else                      printf("Your guess is SOMEWHAT LOW\n");          }    }    if (bGuessedCorrectly == 0)    {          printf("Unforunatly you did not guess it correctly. The correct number is: %d\n", x);    }    }

Output

Welcome to Guess a Word Program (0-100) with in 5 attempts.

Page 28: C Programming With Solutions

ATTEMPT 1: Enter the your number: 50Your guess is MODERATELY HIGHATTEMPT 2: Enter the your number: 28Your guess is SOMEWHAT HIGHATTEMPT 3: Enter the your number: 24Your guess is SOMEWHAT HIGHATTEMPT 4: Enter the your number: 22Your guess is SOMEWHAT LOWATTEMPT 5: Enter the your number: 23Congrats! You have guessed the number correctlyPress any key to continue . . . 

15. Use of break and continue statements

Source Code

  void main(){    int evencount = 0, i = 0;    for(i = 0; ; i++)    {        if(i >= 60)            break; // Terminate the for loop        if((i % 2) != 0)            continue; // Will skip the reminder of the for loop        evencount++;    }    printf(“Total Even Numbers Between 0 – 60 is: %d”, evencount);}

Output

Total Even Numbers Between 0 – 60 is: 31

16. Switch Case Example for Simple Arithmetic Operations

Source Code

#include <stdio.h>  void main(){      int opcode;      int a, b;      int result; 

Page 29: C Programming With Solutions

      printf("Program for Addition, Subtraction, Multiplication and Division\n");      printf("Enter Your Choice: 1 - Add, 2 - Sub, 3 - Mul, 4 - Div: ");      scanf("%d", &opcode);      printf("Enter First Number:");      scanf("%d", &a);      printf("Enter Second Number:");      scanf("%d", &b);       switch(opcode)      {      case 1:            result = a + b;            printf("%d + %d = %d", a, b, result);            break;      case 2:            result = a - b;            printf("%d - %d = %d", a, b, result);            break;      case 3:            result = a * b;            printf("%d * %d = %d", a, b, result);            break;      case 4:            result = a / b;            printf("%d / %d = %d\n%d %% %d = %d", a, b, result, a, b, a % b);            break;      }}

Output

Program for Addition, Subtraction, Multiplication and DivisionEnter Your Choice: 1 - Add, 2 - Sub, 3 - Mul, 4 - Div: 1Enter First Number: 5Enter Second Number: 35 + 3 = 8

Program for Addition, Subtraction, Multiplication and DivisionEnter Your Choice: 1 - Add, 2 - Sub, 3 - Mul, 4 - Div: 2Enter First Number: 5Enter Second Number: 35 - 3 = 2 Program for Addition, Subtraction, Multiplication and DivisionEnter Your Choice: 1 - Add, 2 - Sub, 3 - Mul, 4 - Div: 3Enter First Number: 5Enter Second Number: 35 * 3 = 15

Program for Addition, Subtraction, Multiplication and DivisionEnter Your Choice: 1 - Add, 2 - Sub, 3 - Mul, 4 - Div: 4Enter First Number: 5Enter Second Number: 35 / 3 = 15 % 3 = 2

Page 30: C Programming With Solutions

17. Scroll Text using gotoxy and printf functions

Source Code

 

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <dos.h>

#include <conio.h>

 

 

void scroll(const char *str)

{

    int pos = 1;

    int len = strlen(str);

    char buf[128];

    clrscr();

    while(!kbhit())

    {

      gotoxy(pos,1);

      printf("%s", str);

      delay(100);

      gotoxy(pos,1);

      if(pos > 80 - len)

      {

          sprintf(buf, "%%%ds", len);

          printf(buf, " ");

          pos = 1;

      }

      else

      {

          printf(" ");

      }

      pos++;

    }

}

 

Page 31: C Programming With Solutions

int main(int argc, char *argv[])

{

    char message[64];

 

    if(argc < 2)

    {

      printf("Usage: scroll.exe <text>");

      exit(0);

    }

 

    strcpy(message, (const char*) argv[1]);

 

    scroll(message);

 

    return 0;

Output

C:\TC\Samples> Scroll.exe "welcome to www.google.com" 

17. Guess the Secret Word

Source Code

#include <stdio.h>#include <math.h>#include <conio.h>#include <process.h>#include <string.h> int ReadLine(FILE *fp, char *data, int len){    int index = 0;    while(1)    {        char ch;        if( feof(fp))            break;        if( fread(&ch, 1, 1, fp) < 1)            break; 

Page 32: C Programming With Solutions

        if(ch == '\n')        {            data[index++] = '\0';            break;        }        data[index++] = ch;    }    return index;}  int ReadWordsFromFile(char **p){    int count = 0;    char buf[128];    FILE *istream = fopen("words_input.txt", "r");    if (istream == 0)        return -1;     while(1)    {        if( feof(istream))            break;        if(ReadLine(istream, buf, 128) < 0)            break;        p[count] = (char*) malloc(128);        strcpy(p[count], buf);        count++;    }    fclose(istream);    return count;} void main(){    int count = 0;    char *words[100];    char *secretWord;    int guessX;    int numChars = -1;    int i, j;    int bGuessedCorrectly = 0;     printf("\nWelcome to Guess a Word\n");    count = ReadWordsFromFile(words);    if (count <= 0)    {          printf("\nNo words found in the file");          return;    }

Page 33: C Programming With Solutions

    guessX = rand() % count;    secretWord = words[guessX];     numChars = strlen(secretWord);     printf("Your secret word is: ");    for(i = 0; i < numChars; i++)          printf("*");    printf("\n");     printf("\nGuess now  (To stop the program, enter #) : ");     while (1)    {          char choice[128];        scanf("%s", choice);           if (choice[0] == '#')                break;          if (strcmp(secretWord, choice) == 0)          {                bGuessedCorrectly = 1;                break;          }          for (i = 0; i < numChars; i++)          {                if (i < strlen(secretWord) &&                      i < strlen(choice))                {                      if (secretWord[i] == choice[i])                            printf("%c", choice[i]);                      else                            printf("*");                }                else                      printf("*");          }          printf("\n");     }    if (bGuessedCorrectly == 0)          printf("\nUnforunatly you did not guess it correctly. The secret word is: %s", secretWord);    else          printf("\nCongrats! You have guessed it correctly");     for(i = 0; i < count; i++)        free(words[i]);}

Page 34: C Programming With Solutions

 

Output

// contents of words_input.txtcomputerscienceschoolschoolinginformationtechnology   Welcome to Guess a Word Your secret word is: **********Guess now  (To stop the program, enter #) :victor***h******School**********Tech*ech******technotechno****technologyCongrats! You have guessed it correctly

PROGRAMS FOR BASIC CALUCATIONS:

Simple Student Mark List Preparation

Source Code

#include <stdio.h>#include <conio.h>#include <process.h>#include <string.h> #pragma pack(2)typedef struct _CStudent{    char name[64];    int marks[5];    int total;} CStudent; static int m_nMaxStudents;static CStudent m_studList[100];void AddRecord(const char *name, int *marks);

Page 35: C Programming With Solutions

 void AddRecord(const char *name, int *marks){      int i, pos = m_nMaxStudents;      strcpy(m_studList[pos].name,name);      m_studList[pos].total = 0;      for(i = 0; i < 5; i++)      {            m_studList[pos].marks[i] = marks[i];            m_studList[pos].total += marks[i];;      }      m_nMaxStudents++;} void ViewRecords(){    int i = 0;    printf("_______________________________________________________________\n");    printf("SNo Student Name       Sub1   Sub2   Sub3   Sub4   Sub5   Total\n");    printf("_______________________________________________________________\n");     for(i = 0; i < m_nMaxStudents; i++)    {        printf("%3d %-19s %-6d %-6d %-6d %-6d %-6d %-6d\n",                i + 1,                m_studList[i].name,                m_studList[i].marks[0],                m_studList[i].marks[1],                m_studList[i].marks[2],                m_studList[i].marks[3],                m_studList[i].marks[4],                m_studList[i].total);    }    printf("_______________________________________________________________\n");}  void InputRecords(){      char name[64];      int i, marks[5];       printf("Student Name: ");          scanf("%s", name);           for(i = 1; i <= 5; i++)      {          printf("Sub %d Mark:", i);          scanf("%d", &marks[i-1]);      }

Page 36: C Programming With Solutions

      AddRecord(name, marks);}  int main(){    int i, numStudents = -1;       printf("Welcome to Student MarkList Application\n");    printf("Enter the number of Students: ");     scanf("%d", &numStudents);     for(i = 0; i < numStudents; i++)    {        printf("\n\nEnter the %d student information:\n", i + 1);       InputRecords();    }    ViewRecords();    getch();} 

Output

Welcome to Student MarkList Application

Enter the number of Students: 3

 

 

Enter the 1 student information:

Student Name: AAA

Sub 1 Mark:40

Sub 2 Mark:50

Sub 3 Mark:60

Sub 4 Mark:70

Sub 5 Mark:80

 

 

Enter the 2 student information:

Student Name: BBB

Sub 1 Mark:80

Page 37: C Programming With Solutions

Sub 2 Mark:80

Sub 3 Mark:70

Sub 4 Mark:670

Sub 5 Mark:90

 

 

Enter the 3 student information:

Student Name: CCC

Sub 1 Mark:100

Sub 2 Mark:90

Sub 3 Mark:99

Sub 4 Mark:88

Sub 5 Mark:89

_______________________________________________________________

SNo Student Name       Sub1   Sub2   Sub3   Sub4   Sub5   Total

_______________________________________________________________

  1 AAA                 40     50     60     70     80     300

  2 BBB                 80     80     70     670    90     990

  3 CCC                 100    90     99     88     89     466

_______________________________________________________________

 

2. Kaprekar Transformation 3 Digit Number ends with 495

Source Code

#include <stdio.h>

#include <string.h>

 

 

int ComputeAndPrint(int num)

{

Page 38: C Programming With Solutions

    int a1, a2, a3;

    int d1, d2, d3;

    int big, small, diff;

 

    int digit1 = num / 100; // MSB

    int digit2 = (num - digit1 * 100) / 10;

    int digit3 = (num % 10); // LSB

 

    if(digit1 > digit2)

    {

        if(digit1 > digit3)

        {

            d1 = digit1;

            if(digit2 > digit3)

            {

                d2 = digit2;

                d3 = digit3;

            }

            else

            {

                d3 = digit2;

                d2 = digit3;

            }

        }

        else

        {

            d1 = digit3;

            d2 = digit1;

            d3 = digit2;

        }

    }

    else

    {

        if(digit2 > digit3)

        {

            d1 = digit2;

            if(digit1 > digit3)

            {

                d2 = digit1;

Page 39: C Programming With Solutions

                d3 = digit3;

            }

            else

            {

                d3 = digit1;

                d2 = digit3;

            }

        }

        else

        {

            d1 = digit3;

            d2 = digit2;

            d3 = digit1;

        }

    }

 

 

    if(digit1 < digit2)

    {

        if(digit1 < digit3)

        {

            a1 = digit1;

            if(digit2 < digit3)

            {

                a2 = digit2;

                a3 = digit3;

            }

            else

            {

                a3 = digit2;

                a2 = digit3;

            }

        }

        else

        {

            a1 = digit3;

            a2 = digit1;

            a3 = digit2;

        }

Page 40: C Programming With Solutions

    }

    else

    {

        if(digit2 < digit3)

        {

            a1 = digit2;

            if(digit1 < digit3)

            {

                a2 = digit1;

                a3 = digit3;

            }

            else

            {

                a3 = digit1;

                a2 = digit3;

            }

        }

        else

        {

            a1 = digit3;

            a2 = digit2;

            a3 = digit1;

        }

    }

 

 

    big = d1 * 100 + d2 * 10 + d3;

    small = a1 * 100 + a2 * 10 + a3;

    diff = big - small;

    printf("%d - %d = %d\n", big,small, diff);

 

    return diff;

}

 

int main(int argc, char* argv[])

{

    int num = 0, nextnum = 0;

    int digit1, digit2, digit3;

   

Page 41: C Programming With Solutions

    if(argc < 2 ||

        strlen(argv[1]) != 3)

    {

      printf("3digit.exe <3 digit number>\n");

      exit(0);

    }

    num = atoi(argv[1]);

    if(num < 0 || num > 999)

    {

      printf("Not a valid number\n");

      exit(0);

    }

 

    digit1 = num / 100; // MSB

    digit2 = (num - digit1 * 100) / 10;

    digit3 = (num % 10); // LSB

    if(digit1 == digit2 &&  digit1 == digit3)

    {

      printf("All digits should not be equal\n");

      exit(0);

    }

 

    while(1)

    {

        nextnum = ComputeAndPrint(num);

 

        if(num == nextnum)

            break;

        num = nextnum;

    }

   

      return 0;

}

Output

 

3digit.exe 812

 

821 - 128 = 693

Page 42: C Programming With Solutions

963 - 369 = 594

954 - 459 = 495

954 - 459 = 495

 

 

3digit.exe 576

 

765 - 567 = 198

981 - 189 = 792

972 - 279 = 693

963 - 369 = 594

954 - 459 = 495

954 - 459 = 495

 

 

3digit.exe 417

 

741 - 147 = 594

954 - 459 = 495

954 - 459 = 495

3. Pascal Triangle

Source Code

#include <stdio.h>int main(){      int n, x, y, c, q;      printf("Pascal Triangle Program\n");      printf("Enter the number of rows: ");      scanf("%d",&n);       for (y = 0; y < n; y++)      {            c = 1;            for(q = 0; q < n - y; q++)            {                  printf("%3s", " ");            }            for (x = 0; x <= y; x++)            {                  printf("   %3d ",c);                  c = c * (y - x) / (x + 1);            }            printf("\n");

Page 43: C Programming With Solutions

      }      printf("\n");      return 0;}

Output

Pascal Triangle Program

Enter the number of rows:  11

                                      1

                                   1      1

                                1      2      1

                             1      3      3      1

                          1      4      6      4      1

                       1      5     10     10      5      1

                    1      6     15     20     15      6      1

                 1      7     21     35     35     21      7      1

              1      8     28     56     70     56     28      8      1

           1      9     36     84    126    126     84     36      9      1

        1     10     45    120    210    252    210    120     45     10      1

Page 44: C Programming With Solutions

4.Converting From Lower Case to Upper Case Letters

Source Code

#include <stdio.h>#include <conio.h>#include <ctype.h> void main(){      printf("ESC to break\n");      while(1)      {            char ch = getch();            if( ch == 6)                  break;                       if(islower(ch) != 0)                  putch(toupper(ch));            else                  putch(ch);      }}

Output

ESC to break WELCOME TO GOOGLE . COM

5. Printing Characters on the Screen using getch and putch

Source Code

#include <stdio.h>#include <conio.h> void main(){      char  ch;      printf("Program for printing characters. Enter Esc Key to exit\n");      while(1)      {            ch = getch();            //printf("%d", ch);            if(ch == 27)                  break;            else if(ch == 7)                  printf("\n");            else if(ch == 9)                  printf("\t");            else                  putch(ch);      }}

Page 45: C Programming With Solutions

Output

Program for printing characters. Enter Esc Key to exit 

This is for testing from www.google.com

6. Static Variables For Counting Function Calls

Source Code

#include <stdio.h>

 

void TestFunc()

{

    static int IsFirstTime = 0;

    if(IsFirstTime == 0)

    {

      printf("This function is called as a first time\n");

      IsFirstTime++;

    }

    else

    {

      IsFirstTime++;

      printf("This function has been called %d times so far\n",

IsFirstTime);

    }

}

 

int main()

{

      int i;

      for(i = 0; i < 10; i++)

            TestFunc();

      return 0;

}

Output

This function is called as a first time

This function has been called 2 times so far

Page 46: C Programming With Solutions

This function has been called 3 times so far

This function has been called 4 times so far

This function has been called 5 times so far

This function has been called 6 times so far

This function has been called 7 times so far

This function has been called 8 times so far

This function has been called 9 times so far

This function has been called 10 times so far

Press any key to continue . . .

7. Program to check whether a Number is a palindrome or not

Source Code

// Program for Palindrome of a number// #include <stdio.h>  int main(){    long n, number;    int digits[10], i, index;    int palindrome;     printf("\nProgram to check whether given number is palindrome or not. Enter -1 to exit");    while(1)    {        printf("\nEnter a number:");        scanf("%ld", &n);               if(n < 0)            break;        number = n;        index = 0;        palindrome = 1;        do        {            digits[index++] = n % 10;            n = n / 10;        } while(n > 0);         for(i = 0; i < index / 2 + 1; i++)        {            if(digits[i] != digits[index - 1 - i])            {                palindrome = 0;                break;            }        }         if(palindrome == 1)

Page 47: C Programming With Solutions

            printf("The number %d is a palindrome\n", number);        else            printf("The number %d is NOT a palindrome\n", number);    }      return 0;}

 Click here to download the source code and .EXE application 

Output

Program to check whether given number is palindrome or not. Enter -1 to exit Enter a number:121The number 121 is a palindrome Enter a number:565The number 565 is a palindrome Enter a number:98The number 98 is NOT a palindrome Enter a number:978The number 978 is NOT a palindrome Enter a number:-1

8. Reverse Number

Source Code

#include <stdio.h>#include <conio.h>#include <math.h> int CountNumberOfDigits_usingLog(int n){   return (int) (log10((double)n) + 1);} int CountNumberOfDigits(int n){   int numdgits = 0;   do   {      n = n / 10;      numdgits++;   } while(n > 0);   return numdgits;} void main(){    int i, n, number, numdigits, result;    

Page 48: C Programming With Solutions

    printf("\nProgram to find the reverse of a number. Enter -1 to exit");    while(1)    {        printf("\nEnter a number: ");        scanf("%d", &number);         if(number < 0)            break;        n = number;         numdigits = CountNumberOfDigits(number);               printf("\nNumber of digits in %d is: %d\n", number, numdigits);        result = 0;        for(i = 0; i < numdigits; i++)        {            result *= 10;            result += n % 10;            n = n / 10;        }         printf("The reverse of number %d is : %d\n", number, result);    }}

Output

9. Count Number of Digits in a given Number

Source Code

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

Page 49: C Programming With Solutions

 int CountNumberOfDigits_usingLog(int n){   return (int) (log10((double)n) + 1);} int CountNumberOfDigits(int n){   int numdgits = 0;   do   {      n = n / 10;      numdgits++;   } while(n > 0);   return numdgits;} void main(){    int i, n, number, numdigits, result;        printf("\nProgram to find the reverse of a number. Enter -1 to exit");    while(1)    {        printf("\nEnter a number: ");        scanf("%d", &number);         if(number < 0)            break;        n = number;         numdigits = CountNumberOfDigits(number);               printf("\nNumber of digits in %d is: %d\n", number, numdigits);        result = 0;        for(i = 0; i < numdigits; i++)        {            result *= 10;            result += n % 10;            n = n / 10;        }         printf("The reverse of number %d is : %d\n", number, result);    }}

Output

Page 50: C Programming With Solutions

10. Counting Characters, Words and lines from a file or string buffer

Source Code

 // WordCount.c : Defines the entry point for the console application.

 #include <stdio.h> 

bool GetWordCount(const char *srcFileName, int &numChars, int &numWords, int &numLines){    const int len = 4096;    int nc, wc, lc;    int nBytesRead ;    char buf[4096];       FILE *istream = fopen(srcFileName, "rb");     if (istream == 0)        return false;     numChars = 0;    numWords = 0;    numLines = 0;      do    {        if( feof(istream))            break;

Page 51: C Programming With Solutions

        nBytesRead = fread(buf, 1, len, istream);        if(nBytesRead <= 0)            break;        GetWordCount(buf, nBytesRead, nc, wc, lc);        numChars += nc;        numWords += wc;        numLines += lc;     } while(1);     fclose(istream);    return true;}  int main(){    int nc, wc, lc;    GetWordCount("c:\\kathir.txt", nc, wc, lc);     printf("Chars: %d\n", nc);    printf("Words: %d\n", wc);    printf("Lines: %d\n", lc);     return 0;}

Output

 The file kathir.txt contains the following lines:Welcome to softwareandfinance.com website. Thank you very much for using our web site. The output is given below: Chars: 87Words: 13Lines: 2Press any key to continue . . .

11.Fahrenheit to Celsius ConverterSource Code

// FahrenheitCelsiusConverter.cpp : Implementation File #include <stdio.h> int main(){    double val;    printf("Enter a number to use in Fahrenheit and Celsius Converter: ");    scanf("%lf", &val); 

Page 52: C Programming With Solutions

    double Celsius = (val - 32.0) * 5.0 / 9.0;    double Fahrenheit = (val * (9.0 / 5.0) + 32);     printf("\n%8.4lf %cF = %8.4lf %cC\n", val, 248, Celsius,  248);    printf("%8.4lf %cC = %8.4lf %cF\n\n", val, 248, Fahrenheit,  248);       return 0;}

Output

Enter a number to use in Fahrenheit and Celsius Converter: 100 100.0000 °F =  37.7778 °C100.0000 °C = 212.0000 °F Press any key to continue . . .   Enter a number to use in Fahrenheit and Celsius Converter: -40 -40.0000 °F = -40.0000 °C-40.0000 °C = -40.0000 °F Press any key to continue . . .   Enter a number to use in Fahrenheit and Celsius Converter: 0   0.0000 °F = -17.7778 °C  0.0000 °C =  32.0000 °F Press any key to continue . . .     Enter a number to use in Fahrenheit and Celsius Converter: 28  28.0000 °F =  -2.2222 °C 28.0000 °C =  82.4000 °F Press any key to continue . . .

13. Displaying ASCII Characters On Screen

Source Code

// Printing ASCII characters 

Page 53: C Programming With Solutions

#include <conio.h>#include <process.h>#include <dos.h>#include <stdio.h> int main(){    unsigned char ch ;int x, y;clrscr();

for(unsigned char ch = 0; ch < 255; ch++)    {        printf("%3d = %c\n", ch, ch);    }     printf("\n\n");     return 0;}

Output

  0 =

  1 = ☺

  2 = ☻

  3 = ♥

  4 = ♦

  5 = ♣

  6 = ♠

  7 =

  8 =

  9 =

 10 =

 

 11 = ♂

 12 = ♀

 13 =

 14 = ♫

 15 = ☼

 16 = ►

 17 = ◄

 18 = ↕

 19 = ‼

 20 = ¶

 21 = §

Page 54: C Programming With Solutions

 22 = ▬

 23 = ↨

 24 = ↑

 25 = ↓

 26 = →

 27 = ←

 28 = ∟

 29 = ↔

 30 = ▲

 31 = ▼

 32 =

 33 = !

 34 = "

 35 = #

 36 = $

 37 = %

 38 = &

 39 = '

 40 = (

 41 = )

 42 = *

 43 = +

 44 = ,

 45 = -

 46 = .

 47 = /

 48 = 0

 49 = 1

 50 = 2

 51 = 3

 52 = 4

 53 = 5

 54 = 6

 55 = 7

 56 = 8

 57 = 9

 58 = :

 59 = ;

 60 = <

Page 55: C Programming With Solutions

 61 = =

 62 = >

 63 = ?

 64 = @

 65 = A

 66 = B

 67 = C

 68 = D

 69 = E

 70 = F

 71 = G

 72 = H

 73 = I

 74 = J

 75 = K

 76 = L

 77 = M

 78 = N

 79 = O

 80 = P

 81 = Q

 82 = R

 83 = S

 84 = T

 85 = U

 86 = V

 87 = W

 88 = X

 89 = Y

 90 = Z

 91 = [

 92 = \

 93 = ]

 94 = ^

 95 = _

 96 = `

 97 = a

 98 = b

 99 = c

Page 56: C Programming With Solutions

100 = d

101 = e

102 = f

103 = g

104 = h

105 = i

106 = j

107 = k

108 = l

109 = m

110 = n

111 = o

112 = p

113 = q

114 = r

115 = s

116 = t

117 = u

118 = v

119 = w

120 = x

121 = y

122 = z

123 = {

124 = |

125 = }

126 = ~

127 = ⌂

128 = Ç

129 = ü

130 = é

131 = â

132 = ä

133 = à

134 = å

135 = ç

136 = ê

137 = ë

138 = è

Page 57: C Programming With Solutions

139 = ï

140 = î

141 = ì

142 = Ä

143 = Å

144 = É

145 = æ

146 = Æ

147 = ô

148 = ö

149 = ò

150 = û

151 = ù

152 = ÿ

153 = Ö

154 = Ü

155 = ¢

156 = £

157 = ¥

158 = ₧

159 = ƒ

160 = á

161 = í

162 = ó

163 = ú

164 = ñ

165 = Ñ

166 = ª

167 = º

168 = ¿

169 = ⌐

170 = ¬

171 = ½

172 = ¼

173 = ¡

174 = «

175 = »

176 = ░

177 = ▒

Page 58: C Programming With Solutions

178 = ▓

179 = │

180 = ┤

181 = ╡

182 = ╢

183 = ╖

184 = ╕

185 = ╣

186 = ║

187 = ╗

188 = ╝

189 = ╜

190 = ╛

191 = ┐

192 = └

193 = ┴

194 = ┬

195 = ├

196 = ─

197 = ┼

198 = ╞

199 = ╟

200 = ╚

201 = ╔

202 = ╩

203 = ╦

204 = ╠

205 = ═

206 = ╬

207 = ╧

208 = ╨

209 = ╤

210 = ╥

211 = ╙

212 = ╘

213 = ╒

214 = ╓

215 = ╫

216 = ╪

Page 59: C Programming With Solutions

217 = ┘

218 = ┌

219 = █

220 = ▄

221 = ▌

222 = ▐

223 = ▀

224 = α

225 = ß

226 = Γ

227 = π

228 = Σ

229 = σ

230 = µ

231 = τ

232 = Φ

233 = Θ

234 = Ω

235 = δ

236 = ∞

237 = φ

238 = ε

239 = ∩

240 = ≡

241 = ±

242 = ≥

243 = ≤

244 = ⌠

245 = ⌡

246 = ÷

247 = ≈

248 = °

249 = ∙

250 = ·

251 = √

252 = ⁿ

253 = ²

254 = ■

Press any key to continue . . .

Page 60: C Programming With Solutions

14. Display the numbers containing the digit '5' in between 100 to 200

Source Code

#include <stdio.h>

 int main(){    int sum = 0;    int i, a, b, c;    for(i = 100; i <= 200; i++)    {        a = i % 100;        b = a / 10;        c = a % 10;         if(b == 5 || c == 5)            printf("%d\n", i);               sum += i;    }     printf("\n\nSum = %d\n\n", sum);     return 0; }

Output

105115125135145150151152153154155156157158159165175185

Page 61: C Programming With Solutions

195  Sum = 15150Press any key to continue . . .

ALGEBRA AND GOMENTRY

1. Sum of 0 to N Numbers - n (n+1) / 2

Source Code

#include <stdio.h>

 

void main()

{

    int N, sum = 0;

    printf("Program for sum of all numbers from 0 - N\n");

 

    printf("Enter N: ");

    scanf("%d", &N);

   

    sum = N * (N+1) / 2;

   

    printf("The sum of all numbers between 0 and %d is: %d", N, sum);

}

Output

 

Program for sum of all numbers from 0 - N

Enter N: 100

The sum of all numbers between 0 and 100 is: 5050

 2.Sum of ALL Numbers in the Given Range

Source Code

#include <stdio.h>

 

Page 62: C Programming With Solutions

void main()

{

    int index, begno, endno, sum = 0;

    printf("Program for sum of all numbers in the given range\n");

 

    printf("Enter Beg. No.: ");

    scanf("%d", &begno);

    printf("Enter End. No.: ");

    scanf("%d", &endno);

    index = begno;

 

    for(; index <= endno; index ++)

        sum = sum + index;

   

    printf("The sum of even numbers between %d and %d is: %d", begno,

endno, sum);

}

Output

 

Program for sum of all numbers in the given range

Enter Beg. No.: 1

Enter End. No.: 100

The sum of even numbers between 1 and 100 is: 5050

 

3.Sum of EVEN Numbers in the Given Range

Source Code

#include <stdio.h>

 

void main()

{

    int index, begno, endno, sum = 0;

    printf("Program for sum of even numbers in the given range\n");

 

    printf("Enter Beg. No.: ");

Page 63: C Programming With Solutions

    scanf("%d", &begno);

    printf("Enter End. No.: ");

    scanf("%d", &endno);

    index = begno;

    if( (begno % 2) == 1) // If it ODD, then make it EVEN

        index = begno + 1;

    for(; index <= endno; index += 2)

    {

        sum = sum + index;

    }

    printf("The sum of even numbers between %d and %d is: %d", begno,

endno, sum);

}

Output

 Program for sum of even numbers in the given rangeEnter Beg. No.: 1Enter End. No.: 100The sum of even numbers between 1 and 100 is: 2550 

4. Sum of ODD Numbers in the Given Range

Source Code

#include <stdio.h>

 

void main()

{

    int index, begno, endno, sum = 0;

    printf("Program for sum of odd numbers in the given range");

 

    printf("Enter Beg. No.: ");

    scanf("%d", &begno);

    printf("Enter End. No.: ");

    scanf("%d", &endno);

    index = begno;

    if( (begno % 2) == 0) // If it even, then make it ODD

        index = begno + 1;

    for(; index <= endno; index += 2)

    {

Page 64: C Programming With Solutions

        sum = sum + index;

    }

    printf("The sum of odd numbers between %d and %d is: %d", begno,

endno, sum);

Output

 Program for sum of odd numbers in the given rangeEnter Beg. No.: 1Enter End. No.: 100The sum of odd numbers between 1 and 100 is: 2500 

5. Distance between the two points

Source Code

#include <stdio.h>

#include <math.h>

 

void main()

{

    float distance;

    int x1, y1, x2, y2;

    int dx, dy;

 

    printf("Program for distance between the two points\n");

 

    printf("Enter X1: ");

    scanf("%d", &x1);

 

    printf("Enter Y1: ");

    scanf("%d", &y1);

 

    printf("Enter X2: ");

    scanf("%d", &x2);

 

    printf("Enter Y2: ");

    scanf("%d", &y2);

 

Page 65: C Programming With Solutions

    dx = x2 - x1;

    dy = y2 - y1;

 

    distance = sqrt(dx*dx + dy*dy);

    printf("%.4f", distance);

}

Output

 

Program for distance between the two points

Enter X1: 10

Enter Y1: 10

Enter X2: 30

Enter Y2: 30

Distance between (10, 10) and (30, 30) = SQRT(800) = 28.2843 

6. Finding the equation of a Line Given Two End Points

Source Code

#include <stdio.h>

#include <math.h>

 

void main()

{

    float slope, intercept;

    float x1, y1, x2, y2;

    float dx, dy;

 

    printf("Program to find the equation of a line given two end points\

n");

 

    printf("Enter X1: ");

    scanf("%f", &x1);

 

    printf("Enter Y1: ");

    scanf("%f", &y1);

 

    printf("Enter X2: ");

    scanf("%f", &x2);

Page 66: C Programming With Solutions

 

    printf("Enter Y2: ");

    scanf("%f", &y2);

 

    dx = x2 - x1;

    dy = y2 - y1;

 

    slope = dy / dx;

    // y = mx + c

    // intercept c = y - mx

    intercept = y1 - slope * x1; // which is same as y2 - slope * x2

 

    printf("Equation of the line with end points (%.2f, %.2f) and (%.2f,

%.2f) : Y = %.2fX %c %.2f\n", x1, y1, x2, y2, slope, (intercept < 0) ? '

' : '+',  intercept);

}

Output

 

Program to find the equation of a line given two end points

Enter X1: 2

Enter Y1: 3

Enter X2: 5

Enter Y2: 7

Equation of the line with end points (2, 3 and (5, 7) : Y = 1.33333X

+0.333333

Press any key to continue . . . 

7. Calculating Slope of a Line Given Two End Points

Source Code

#include <stdio.h>

#include <math.h>

 

void main()

{

    float slope;

    float x1, y1, x2, y2;

Page 67: C Programming With Solutions

    float dx, dy;

 

    printf("Program to find the slope of a line given two end points\

n");

 

    printf("Enter X1: ");

    scanf("%f", &x1);

 

    printf("Enter Y1: ");

    scanf("%f", &y1);

 

    printf("Enter X2: ");

    scanf("%f", &x2);

 

    printf("Enter Y2: ");

    scanf("%f", &y2);

 

    dx = x2 - x1;

    dy = y2 - y1;

 

    slope = dy / dx;

    printf("Slope of the line with end points (%.4f, %.4f) and (%.4f,

%.4f) = %.4f", x1, y1, x2, y2, slope);

}

Output

 

Program to find the slope of a line given two end points

Enter X1: 2.5

Enter Y1: 7.5

Enter X2: 12.5

Enter Y2: 18

Slope of the line with end points (2.5, 7.5 and (12.5, 18) = 1.05

Press any key to continue . . . 

8. Check whether given point lies on a Line (Y = MX + C)

Source Code

Page 68: C Programming With Solutions

#include <stdio.h>

#include <math.h>

 

void main()

{

    float slope, intercept;

    float px, py;

 

    printf("Program to find whether the given point lies on a line:\n");

    printf("Enter Line1 - Slope: ");

    scanf("%f", &slope);

 

    printf("Enter Line1 - Intercept: ");

    scanf("%f", &intercept);

 

    printf("Enter Point X: ");

    scanf("%f", &px);

 

    printf("Enter Point Y: ");

    scanf("%f", &py);

 

   

    printf("Equation of the line: ");

    printf("%.2fX %c %.2f\n", slope, ((intercept < 0) ? ' ' : '+'),

intercept);

 

    if( slope * px + intercept > (py - 0.01) &&

        slope * px + intercept < (py + 0.01))

    {

           printf("Given point lies on the line\n");

    }

    else

        printf("Given point is outside the line\n");

}

Output

Program to find whether the given point lies on a line:

Enter Line1 - Slope: 1.25

Page 69: C Programming With Solutions

Enter Line1 - Intercept: 0.75

Enter Point X: 2.33

Enter Point Y: 3.67

Equation of the line: 1.25X +0.75

Given point lies on the line

Press any key to continue . . .

 

9. Check whether given point lies on a Line Segment

Source Code

#include <stdio.h>

#include <math.h>

 

void main()

{

    float slope, intercept;

    float x1, y1, x2, y2;

    float px, py;

    float left, top, right, bottom; // Bounding Box For Line Segment

    float dx, dy;

 

    printf("Program to find whether the given point lies with in line

segment:\n");

 

    printf("Enter X1: ");

    scanf("%f", &x1);

 

    printf("Enter Y1: ");

    scanf("%f", &y1);

 

    printf("Enter X2: ");

    scanf("%f", &x2);

 

    printf("Enter Y2: ");

    scanf("%f", &y2);

 

    printf("Enter Point X: ");

    scanf("%f", &px);

Page 70: C Programming With Solutions

 

    printf("Enter Point Y: ");

    scanf("%f", &py);

 

    dx = x2 - x1;

    dy = y2 - y1;

 

    slope = dy / dx;

    // y = mx + c

    // intercept c = y - mx

    intercept = y1 - slope * x1; // which is same as y2 - slope * x2

 

    // For Bounding Box

    if(x1 < x2)

    {

        left = x1;

        right = x2;

    }

    else

    {

        left = x2;

        right = x1;

    }

    if(y1 < y2)

    {

        top = y1;

        bottom = y2;

    }

    else

    {

        top = y1;

        bottom = y2;

    }

 

 

    printf("Equation of the line: %.2f X %c %.2f\n", slope, ((intercept

< 0) ? ' ' : '+'), intercept);

   

    if( slope * px + intercept > (py - 0.01) &&

Page 71: C Programming With Solutions

        slope * px + intercept < (py + 0.01))

    {

        if( px >= left && px <= right && 

            py >= top && py <= bottom )

        {

            printf("Given point lies in the line segment\n");

        }

        else

            printf("Given point is outside the line segment\n"); 

    }

    else

        printf("The point is outside the line segment\n");

   }

Output

Program to find whether the given point lies with in line segment:

Enter X1: 1

Enter Y1: 2

Enter X2: 5

Enter Y2: 7

Enter Point X: 2.33

Enter Point Y: 3.67

Equation of the line: 1.25X +0.75

Given point lies in the line segment

Press any key to continue . . .

 

 

 

Program to find whether the given point lies with in line segment:

Enter X1: 1

Enter Y1: 2

Enter X2: 5

Enter Y2: 7

Enter Point X: 2.3

Enter Point Y: 3.6

Equation of the line: 1.25X +0.75

The point is outside the line segment

Press any key to continue . . .

Page 72: C Programming With Solutions

10. Finding the Intersection of two Lines Given End Points of Two Lines

Source Code

#include <stdio.h>

#include <math.h>

 

void main()

{

    float m1, c1, m2, c2;

    float x1, y1, x2, y2;

    float dx, dy;

    float intersection_X, intersection_Y;

 

    printf("Program to find the intersecting point of two lines:\n");

 

    printf("Enter Line1 - X1: ");

    scanf("%f", &x1);

 

    printf("Enter Line1 - Y1: ");

    scanf("%f", &y1);

 

    printf("Enter Line1 - X2: ");

    scanf("%f", &x2);

 

    printf("Enter Line1 - Y2: ");

    scanf("%f", &y2);

 

    dx = x2 - x1;

    dy = y2 - y1;

 

    m1 = dy / dx;

    // y = mx + c

    // intercept c = y - mx

    c1 = y1 - m1 * x1; // which is same as y2 - slope * x2

 

    printf("Enter Line2 - X1: ");

    scanf("%f", &x1);

Page 73: C Programming With Solutions

 

    printf("Enter Line2 - Y1: ");

    scanf("%f", &y1);

 

    printf("Enter Line2 - X2: ");

    scanf("%f", &x2);

 

    printf("Enter Line2 - Y2: ");

    scanf("%f", &y2);

 

    dx = x2 - x1;

    dy = y2 - y1;

 

    m2 = dy / dx;

    // y = mx + c

    // intercept c = y - mx

    c2 = y1 - m2 * x1; // which is same as y2 - slope * x2

 

    printf("Equation of line1: Y = %.2fX %c %.2f\n", m1, (c1 < 0) ? '

' : '+',  c1);

    printf("Equation of line2: Y = %.2fX %c %.2f\n", m2, (c2 < 0) ? '

' : '+',  c2);

 

    if( (m1 - m2) == 0)

        printf("No Intersection between the lines\n");

    else

    {

        intersection_X = (c2 - c1) / (m1 - m2);

        intersection_Y = m1 * intersection_X + c1;

        printf("Intersecting Point: = %.2f, %.2f\n", intersection_X,

intersection_Y);

    }

}

Output

 

Program to find the intersecting point of two lines:

Enter Line1 - X1: 1

Enter Line1 - Y1: 2

Page 74: C Programming With Solutions

Enter Line1 - X2: 5

Enter Line1 - Y2: 7

Enter Line2 - X1: 3

Enter Line2 - Y1: 3

Enter Line2 - X2: 4

Enter Line2 - Y2: 5

Equation of line1: Y = 1.25X + 0.75

Equation of line2: Y = 2.00X   -3.00

Intersecting Point: = 5.00, 7.00

 

Press any key to continue . . .

 

Program to find the intersecting point of two lines:

Enter Line1 - X1: 1

Enter Line1 - Y1: 3

Enter Line1 - X2: 5

Enter Line1 - Y2: 7

Enter Line2 - X1: 4

Enter Line2 - Y1: 6

Enter Line2 - X2: 8

Enter Line2 - Y2: 10

Equation of line1: Y = 1.00X + 2.00

Equation of line2: Y = 1.00X + 2.00

No Intersection between the lines

 Press any key to continue . . .

 

11. Finding the Intersection of two Line Segments Given End Points of Two Lines

Source Code

#include <stdio.h>

#include <math.h>

 

 

int IsPointInBoundingBox(float x1, float y1, float x2, float y2, float p

x, float py)

Page 75: C Programming With Solutions

{

    float left, top, right, bottom; // Bounding Box For Line Segment

    // For Bounding Box

    if(x1 < x2)

    {

        left = x1;

        right = x2;

    }

    else

    {

        left = x2;

        right = x1;

    }

    if(y1 < y2)

    {

        top = y1;

        bottom = y2;

    }

    else

    {

        top = y1;

        bottom = y2;

    }

 

    if( (px+0.01) >= left && (px-0.01) <= right && 

            (py+0.01) >= top && (py-0.01) <= bottom )

    {

        return 1;

    }

    else

        return 0;

}

 

int LineIntersection(float l1x1, float l1y1, float l1x2, float l1y2,

                            float l2x1, float l2y1, float l2x2, float l2

y2,

                            float *m1, float *c1, float *m2, float *c2,

                            float* intersection_X, float*

intersection_Y)

Page 76: C Programming With Solutions

{

    float dx, dy;

 

    dx = l1x2 - l1x1;

    dy = l1y2 - l1y1;

 

    *m1 = dy / dx;

    // y = mx + c

    // intercept c = y - mx

    *c1 = l1y1 - *m1 * l1x1; // which is same as y2 - slope * x2

 

    dx = l2x2 - l2x1;

    dy = l2y2 - l2y1;

 

    *m2 = dy / dx;

    // y = mx + c

    // intercept c = y - mx

    *c2 = l2y1 - *m2 * l2x1; // which is same as y2 - slope * x2

 

    if( (*m1 - *m2) == 0)

        return 0;

    else

    {

        *intersection_X = (*c2 - *c1) / (*m1 - *m2);

        *intersection_Y = *m1 * *intersection_X + *c1;

    }

}

 

int LineSegmentIntersection(float l1x1, float l1y1, float l1x2, float l1

y2,

                            float l2x1, float l2y1, float l2x2, float l2

y2,

                            float *m1, float *c1, float *m2, float *c2,

                            float* intersection_X, float*

intersection_Y)

{

    float dx, dy;

 

    dx = l1x2 - l1x1;

Page 77: C Programming With Solutions

    dy = l1y2 - l1y1;

 

    *m1 = dy / dx;

    // y = mx + c

    // intercept c = y - mx

    *c1 = l1y1 - *m1 * l1x1; // which is same as y2 - slope * x2

 

    dx = l2x2 - l2x1;

    dy = l2y2 - l2y1;

 

    *m2 = dy / dx;

    // y = mx + c

    // intercept c = y - mx

    *c2 = l2y1 - *m2 * l2x1; // which is same as y2 - slope * x2

 

    if( (*m1 - *m2) == 0)

        return 0;

    else

    {

        *intersection_X = (*c2 - *c1) / (*m1 - *m2);

        *intersection_Y = *m1 * *intersection_X + *c1;

    }

    if(IsPointInBoundingBox(l1x1, l1y1, l1x2, l1y2, *intersection_X,

*intersection_Y) == 1 &&

        IsPointInBoundingBox(l2x1, l2y1, l2x2, l2y2, *intersection_X,

*intersection_Y) == 1)

        return 1;

    else

        return 0;

}

 

void main()

{

    float m1, c1, m2, c2;

    float l1x1, l1y1, l1x2, l1y2;

    float l2x1, l2y1, l2x2, l2y2;

    float intersection_X, intersection_Y;

    int nRet;

 

Page 78: C Programming With Solutions

    printf("Program to find the intersection point of two line

segments:\n");

 

    printf("Enter Line1 - X1: ");

    scanf("%f", &l1x1);

 

    printf("Enter Line1 - Y1: ");

    scanf("%f", &l1y1);

 

    printf("Enter Line1 - X2: ");

    scanf("%f", &l1x2);

 

    printf("Enter Line1 - Y2: ");

    scanf("%f", &l1y2);

 

    printf("Enter Line2 - X1: ");

    scanf("%f", &l2x1);

 

    printf("Enter Line2 - Y1: ");

    scanf("%f", &l2y1);

 

    printf("Enter Line2 - X2: ");

    scanf("%f", &l2x2);

 

    printf("Enter Line2 - Y2: ");

    scanf("%f", &l2y2);

 

 

    nRet = LineSegmentIntersection(l1x1, l1y1, l1x2, l1y2,

                            l2x1, l2y1, l2x2, l2y2,

                            &m1, &c1, &m2, &c2, &intersection_X,

&intersection_Y);

 

    printf("Equation of line1: Y = %.2fX %c %.2f\n", m1, (c1 < 0) ? '

' : '+',  c1);

    printf("Equation of line2: Y = %.2fX %c %.2f\n", m2, (c2 < 0) ? '

' : '+',  c2);

 

    if(nRet == 0)

Page 79: C Programming With Solutions

        printf("The two line segments do not intersect each other");

    else

        printf("The two line segments intersect each other at %.2f,

%.2f", intersection_X, intersection_Y);

 

}

Output

 

Program to find the intersection point of two line segments:

Enter Line1 - X1: 1

Enter Line1 - Y1: 2

Enter Line1 - X2: 5

Enter Line1 - Y2: 7

Enter Line2 - X1: 3

Enter Line2 - Y1: 3

Enter Line2 - X2: 2.33

Enter Line2 - Y2: 3.66

Equation of line1: Y = 1.25X + 0.75

Equation of line2: Y = -0.99X + 5.96

The two line segments do not intersect each other

 

Press any key to continue . . .

12. Check whether a point is inside or outside the Circle

Source Code

 

#include <stdio.h>

#include <math.h>

 

 

void main()

{

    int nCountIntersections = 0;

    float x, y, cx, cy, radius;

    float distance;

    printf("Program to find the given point inside or outside the

circle:\n");

Page 80: C Programming With Solutions

   

    printf("Enter Center Point - X: ");

    scanf("%f", &cx);

 

    printf("Enter Center Point - Y: ");

    scanf("%f", &cy);

 

    printf("Enter Radius: ");

    scanf("%f", &radius);

 

    printf("Enter Point - X: ");

    scanf("%f", &x);

 

    printf("Enter Point - Y: ");

    scanf("%f", &y);

 

    distance = sqrt( (double)(cx-x)*(cx-x) + (cy-y)*(cy-y));

   

    printf("\nDistance between the point and center of the circle:

%.4f", distance);

    if(distance <= radius)

        printf("\nGiven point is inside the circle");

    else

        printf("\nGiven point is outside the circle");

}

Output

 

Program to find the given point inside or outside the circle:

Enter Center Point - X: 10

Enter Center Point - Y: 10

Enter Radius: 7

Enter Point - X: 12

Enter Point - Y: 4

 

Distance between the point and center of the circle: 6.32456

Given point is inside the circle  

Page 81: C Programming With Solutions

13. Check whether a point is Inside a Triangle or Not

Source Code

 

#include <stdio.h>

#include <math.h>

 

 

int IsPointInBoundingBox(float x1, float y1, float x2, float y2, float p

x, float py)

{

    float left, top, right, bottom; // Bounding Box For Line Segment

 

    // For Bounding Box

    if(x1 < x2)

    {

        left = x1;

        right = x2;

    }

    else

    {

        left = x2;

        right = x1;

    }

 

    if(y1 < y2)

    {

        top = y1;

        bottom = y2;

    }

    else

    {

        top = y2;

        bottom = y1;

    }

 

    if( (px+0.01) >= left && (px-0.01) <= right && 

            (py+0.01) >= top && (py-0.01) <= bottom )

    {

Page 82: C Programming With Solutions

        return 1;

    }

    else

        return 0;

 

}

 

 

 

int LineSegmentIntersection(float l1x1, float l1y1, float l1x2, float l1

y2,

                            float l2x1, float l2y1, float l2x2, float l2

y2,

                            float *m1, float *c1, float *m2, float *c2,

                            float* intersection_X, float*

intersection_Y)

{

 

    float dx, dy;

 

    dx = l1x2 - l1x1;

    dy = l1y2 - l1y1;

 

    *m1 = dy / dx;

 

    // y = mx + c

    // intercept c = y - mx

    *c1 = l1y1 - *m1 * l1x1; // which is same as y2 - slope * x2

 

    dx = l2x2 - l2x1;

    dy = l2y2 - l2y1;

 

    *m2 = dy / dx;

    // y = mx + c

    // intercept c = y - mx

    *c2 = l2y1 - *m2 * l2x1; // which is same as y2 - slope * x2

 

    if( (*m1 - *m2) == 0)

        return 0;

Page 83: C Programming With Solutions

    else

    {

        *intersection_X = (*c2 - *c1) / (*m1 - *m2);

        *intersection_Y = *m1 * *intersection_X + *c1;

    }

 

    if(IsPointInBoundingBox(l1x1, l1y1, l1x2, l1y2, *intersection_X,

*intersection_Y) == 1 && IsPointInBoundingBox(l2x1, l2y1, l2x2, l2y2,

*intersection_X, *intersection_Y) == 1)

    {

        return 1;

    }

    else

        return 0;

}

 

int Calculate_Area_Perimeter_Triangle(float ax, float ay, float bx, floa

t by, float cx, floatcy, float *perimeter, float *area)

{

    float A = sqrt((double)(bx-ax) * (bx-ax) + (by-ay) * (by-ay));

    float B = sqrt((double)(bx-cx) * (bx-cx) + (by-cy) * (by-cy));

    float C = sqrt((double)(ax-cx) * (ax-cx) + (ay-cy) * (ay-cy));

    float height = 0;

 

    // Heron's formula for area calculation

    // area = sqrt( s * (s-a) * (s-b) * (s-c))

    float s = (A + B + C) / 2;

 

    *perimeter = A + B + C;

   

    *area = sqrt( s * (s-A) * (s-B) * (s-C));

 

    // area = 1/2 * base * height

    // if side A is base, then height

    height = (*area * 2) / A;

  

    return 1;

}

 

Page 84: C Programming With Solutions

int Calculate_Triangle_Type(float ax, float ay, float bx, float by, floa

t cx, float cy, float*angleA, float *angleB, float *angleC)

{

    float m1, c1, m2, c2;

    float intersection_X, intersection_Y;

    // Find the angle between Line AB and BC

    LineSegmentIntersection(ax, ay, bx, by, bx, by, cx, cy,

                            &m1, &c1, &m2, &c2, &intersection_X,

&intersection_Y);

    *angleB = atan( (m1 - m2) / (1 + m1 * m2)) * 180 / 3.1417;

   

 

    // Find the angle between Line BC and AC

    LineSegmentIntersection(bx, by, cx, cy, cx, cy, ax, ay,

                            &m1, &c1, &m2, &c2, &intersection_X,

&intersection_Y);

    *angleC = atan( (m1 - m2) / (1 + m1 * m2)) * 180 / 3.1417;

   

 

    // Find the angle between Line AC and AB

    LineSegmentIntersection(cx, cy, ax, ay, ax, ay, bx, by,

                            &m1, &c1, &m2, &c2, &intersection_X,

&intersection_Y);

    *angleA = atan( (m1 - m2) / (1 + m1 * m2)) * 180 / 3.1417;

 

    if(*angleA < 90 && *angleB < 90 && *angleC < 90)

        return 1; // Acute Triangle

    else if(*angleA > 90 || *angleB > 90 || *angleC > 90)

        return 2; // obtuse Triangle

    else

        return 3; // Rightangle Triangle

}

 

 

void main()

{

    float m1, c1, m2, c2;

    float intersection_X, intersection_Y;

    float ax, ay, bx, by, cx, cy;

Page 85: C Programming With Solutions

    float perimeter, area;

    float angleA, angleB, angleC;

    float x, y, px, py;

    int type = 0;

    float total = 0;

 

    int nCountIntersections = 0;

    printf("Program to find the given point inside or outside the

triangle:\n");

   

    printf("Enter Triangle Point A - X: ");

    scanf("%f", &ax);

 

    printf("Enter Triangle Point A - Y: ");

    scanf("%f", &ay);

 

    printf("Enter Triangle Point B - X: ");

    scanf("%f", &bx);

 

    printf("Enter Triangle Point B - Y: ");

    scanf("%f", &by);

 

    printf("Enter Triangle Point C - X: ");

    scanf("%f", &cx);

 

    printf("Enter Triangle Point C - Y: ");

    scanf("%f", &cy);

 

    printf("Enter Point - X: ");

    scanf("%f", &x);

 

    printf("Enter Point - Y: ");

    scanf("%f", &y);

 

    px = x + 1000;

    py = y;

 

 

Page 86: C Programming With Solutions

    nCountIntersections += LineSegmentIntersection(ax, ay, bx, by, x, y,

px, py,

                            &m1, &c1, &m2, &c2, &intersection_X,

&intersection_Y);

 

    nCountIntersections += LineSegmentIntersection(ax, ay, cx, cy, x, y,

px, py,

                            &m1, &c1, &m2, &c2, &intersection_X,

&intersection_Y);

 

    nCountIntersections += LineSegmentIntersection(cx, cy, bx, by, x, y,

px, py,

                            &m1, &c1, &m2, &c2, &intersection_X,

&intersection_Y);

 

    if( (nCountIntersections % 2) == 1)

        printf("The Given Point is inside the triangle\n");

    else

        printf("The Given Point is outside the triangle\n");

  

 

    Calculate_Area_Perimeter_Triangle(ax, ay, bx, by, cx, cy,

&perimeter, &area);

 

    printf("\nPerimeter: %.4f", perimeter);

    printf("\nArea:  %.4f", area);

 

    type = Calculate_Triangle_Type(ax, ay, bx, by, cx, cy, &angleA,

&angleB, &angleC);

    total = angleA + angleB + angleC;

 

    if(type == 1)

        printf("\nAcute Triangle");

    else if(type == 2)

        printf("\nObtuse Triangle");

    else if(type == 3)

        printf("\nRight Triangle");

 

    printf("\n");

Page 87: C Programming With Solutions

}

 

Page 88: C Programming With Solutions

Output

 

Program to find the given point inside or outside the triangle:

Enter Triangle Point A - X: 10

Enter Triangle Point A - Y: 10

Enter Triangle Point B - X: 20

Enter Triangle Point B - Y: 10

Enter Triangle Point C - X: 15

Enter Triangle Point C - Y: 15

Enter Point - X: 12

Enter Point - Y: 12

The Given Point is outside the triangle

 

Perimeter: 24.1421

Area: 25

Acute Triangle

Press any key to continue . . .

 

 

 

 

Program to find the given point inside or outside the triangle:

Enter Triangle Point A - X: 10

Enter Triangle Point A - Y: 10

Enter Triangle Point B - X: 20

Enter Triangle Point B - Y: 10

Enter Triangle Point C - X: 15

Enter Triangle Point C - Y: 15

Enter Point - X: 15

Enter Point - Y: 11

The Given Point is inside the triangle

 

Perimeter: 24.1421

Area:  25.0000

Acute Triangle

 

Press any key to continue . . .  

Page 89: C Programming With Solutions

14. Find Area and Perimeter of a Triangle Given 3 points

Source Code

#include <stdio.h>

#include <math.h>

 

 

int Calculate_Area_Perimeter_Triangle(float ax, float ay, float bx, floa

t by, float cx, floatcy, float *perimeter, float *area)

{

    float A = sqrt((double)(bx-ax) * (bx-ax) + (by-ay) * (by-ay));

    float B = sqrt((double)(bx-cx) * (bx-cx) + (by-cy) * (by-cy));

    float C = sqrt((double)(ax-cx) * (ax-cx) + (ay-cy) * (ay-cy));

    float height = 0;

 

    // Heron's formula for area calculation

    // area = sqrt( s * (s-a) * (s-b) * (s-c))

    float s = (A + B + C) / 2;

 

    *perimeter = A + B + C;

   

    *area = sqrt( s * (s-A) * (s-B) * (s-C));

 

    // area = 1/2 * base * height

    // if side A is base, then height

    height = (*area * 2) / A;

  

    return 1;

}

 

void main()

{

    float m1, c1, m2, c2;

    float ax, ay, bx, by, cx, cy;

    float perimeter, area;

    float angleA, angleB, angleC;

    int type = 0;

    float total = 0;

 

Page 90: C Programming With Solutions

    printf("Program to find the Area and Perimeter of a triangle:\n");

   

    printf("Enter Triangle Point A - X: ");

    scanf("%f", &ax);

 

    printf("Enter Triangle Point A - Y: ");

    scanf("%f", &ay);

 

    printf("Enter Triangle Point B - X: ");

    scanf("%f", &bx);

 

    printf("Enter Triangle Point B - Y: ");

    scanf("%f", &by);

 

    printf("Enter Triangle Point C - X: ");

    scanf("%f", &cx);

 

    printf("Enter Triangle Point C - Y: ");

    scanf("%f", &cy);

 

    Calculate_Area_Perimeter_Triangle(ax, ay, bx, by, cx, cy,

&perimeter, &area);

 

    printf("\nPerimeter: %.4f", perimeter);

    printf("\nArea:  %.4f", area);

 

    printf("\n");

}

 

Output

 

Program to find the given type of the triangle:

Enter Triangle Point A - X: 10

Enter Triangle Point A - Y: 10

Enter Triangle Point B - X: 20

Enter Triangle Point B - Y: 10

Enter Triangle Point C - X: 15

Enter Triangle Point C - Y: 15

Page 91: C Programming With Solutions

 

Perimeter: 24.1421

Area:  25.0000

Press any key to continue . . .  

15. Find Acute, Obtuse or Right Angle Triangle Given 3 points

Source Code

#include <stdio.h>

#include <math.h>

 

 

int IsPointInBoundingBox(float x1, float y1, float x2, float y2, float p

x, float py)

{

    float left, top, right, bottom; // Bounding Box For Line Segment

 

    // For Bounding Box

    if(x1 < x2)

    {

        left = x1;

        right = x2;

    }

    else

    {

        left = x2;

        right = x1;

    }

 

    if(y1 < y2)

    {

        top = y1;

        bottom = y2;

    }

    else

Page 92: C Programming With Solutions

    {

        top = y2;

        bottom = y1;

    }

 

    if( (px+0.01) >= left && (px-0.01) <= right && 

            (py+0.01) >= top && (py-0.01) <= bottom )

    {

        return 1;

    }

    else

        return 0;

 

}

 

 

int LineSegmentIntersection(float l1x1, float l1y1, float l1x2, float l1

y2,

                            float l2x1, float l2y1, float l2x2, float l2

y2,

                            float *m1, float *c1, float *m2, float *c2,

                            float* intersection_X, float*

intersection_Y)

{

 

    float dx, dy;

 

    dx = l1x2 - l1x1;

    dy = l1y2 - l1y1;

 

    *m1 = dy / dx;

 

    // y = mx + c

    // intercept c = y - mx

    *c1 = l1y1 - *m1 * l1x1; // which is same as y2 - slope * x2

 

    dx = l2x2 - l2x1;

    dy = l2y2 - l2y1;

 

Page 93: C Programming With Solutions

    *m2 = dy / dx;

    // y = mx + c

    // intercept c = y - mx

    *c2 = l2y1 - *m2 * l2x1; // which is same as y2 - slope * x2

 

    if( (*m1 - *m2) == 0)

        return 0;

    else

    {

        *intersection_X = (*c2 - *c1) / (*m1 - *m2);

        *intersection_Y = *m1 * *intersection_X + *c1;

    }

 

    if(IsPointInBoundingBox(l1x1, l1y1, l1x2, l1y2, *intersection_X,

*intersection_Y) == 1 && IsPointInBoundingBox(l2x1, l2y1, l2x2, l2y2,

*intersection_X, *intersection_Y) == 1)

    {

        return 1;

    }

    else

        return 0;

}

 

int Calculate_Triangle_Type(float ax, float ay, float bx, float by, floa

t cx, float cy, float*angleA, float *angleB, float *angleC)

{

    float m1, c1, m2, c2;

    float intersection_X, intersection_Y;

    // Find the angle between Line AB and BC

    LineSegmentIntersection(ax, ay, bx, by, bx, by, cx, cy,

                            &m1, &c1, &m2, &c2, &intersection_X,

&intersection_Y);

    *angleB = atan( (m1 - m2) / (1 + m1 * m2)) * 180 / 3.1417;

   

 

    // Find the angle between Line BC and AC

    LineSegmentIntersection(bx, by, cx, cy, cx, cy, ax, ay,

                            &m1, &c1, &m2, &c2, &intersection_X,

&intersection_Y);

Page 94: C Programming With Solutions

    *angleC = atan( (m1 - m2) / (1 + m1 * m2)) * 180 / 3.1417;

   

 

    // Find the angle between Line AC and AB

    LineSegmentIntersection(cx, cy, ax, ay, ax, ay, bx, by,

                            &m1, &c1, &m2, &c2, &intersection_X,

&intersection_Y);

    *angleA = atan( (m1 - m2) / (1 + m1 * m2)) * 180 / 3.1417;

 

    if(*angleA < 90 && *angleB < 90 && *angleC < 90)

        return 1; // Acute Triangle

    else if(*angleA > 90 || *angleB > 90 || *angleC > 90)

        return 2; // obtuse Triangle

    else

        return 3; // Rightangle Triangle

}

 

 

void main()

{

    float m1, c1, m2, c2;

    float ax, ay, bx, by, cx, cy;

    float angleA, angleB, angleC;

    int type = 0;

    float total = 0;

 

    printf("Program to find the type of a triangle:\n");

   

    printf("Enter Triangle Point A - X: ");

    scanf("%f", &ax);

 

    printf("Enter Triangle Point A - Y: ");

    scanf("%f", &ay);

 

    printf("Enter Triangle Point B - X: ");

    scanf("%f", &bx);

 

    printf("Enter Triangle Point B - Y: ");

    scanf("%f", &by);

Page 95: C Programming With Solutions

 

    printf("Enter Triangle Point C - X: ");

    scanf("%f", &cx);

 

    printf("Enter Triangle Point C - Y: ");

    scanf("%f", &cy);

 

    type = Calculate_Triangle_Type(ax, ay, bx, by, cx, cy, &angleA,

&angleB, &angleC);

    total = angleA + angleB + angleC;

 

    printf("Angle between the lines is %.4f, %.4f, %.4f\n", angleA,

angleB, angleC);

    if(type == 1)

        printf("\nAcute Triangle");

    else if(type == 2)

        printf("\nObtuse Triangle");

    else if(type == 3)

        printf("\nRight  Triangle");

 

    printf("\n");

}

Output

 

Program to find the type of a triangle:

Enter Triangle Point A - X: 1

Enter Triangle Point A - Y: 1

Enter Triangle Point B - X: 20

Enter Triangle Point B - Y: 10

Enter Triangle Point C - X: 10

Enter Triangle Point C - Y: 20

Angle between the lines is 39.3063, 70.3438, 70.3438

 

Acute Triangle

Press any key to continue . . .

 

Page 96: C Programming With Solutions

16. Check Perfect Square

Source Code

#include <stdio.h>#include <string.h>#include <math.h>

 

int CheckPerfectSquare(int num){    int min = 0, max = 1000;    int answer = 0;    int test = 0;    while(1)    {        test = (min + max) / 2;        answer = test * test;        if( num > answer)        {            // min needs be moved            min = test;        }        else if(num < answer)        {            // max needs be moved            max = test;        }        if(num == answer)        {           printf("\n%d is a perfect square of %d", num, test);           return 1; // perfect square        }        if((max - min) <= 1)        {            printf("\n %d is NOT a perfect square", num);            return 0; // Not a perfect square        }    }    return 0;} int main(){    CheckPerfectSquare(25);    CheckPerfectSquare(36);    CheckPerfectSquare(49);    CheckPerfectSquare(64);    CheckPerfectSquare(68);    CheckPerfectSquare(127);    printf("\n");     return 0;}

Page 97: C Programming With Solutions

Output

25 is a perfect square of 536 is a perfect square of 649 is a perfect square of 764 is a perfect square of 868 is NOT a perfect square127 is NOT a perfect square

17. Generating Prime Numbers

Source Code

#include <stdio.h>

 

int IsPrimeNumber(int num)

{

    int bPrime = 1;

    int factor = num / 2;

    int i = 0;

 

    for(i = 2; i <= factor; i++)

    {

      if( (num % i) == 0)

          bPrime = 0;

    }

 

    return bPrime;

}

 

 

void GeneratePrimeNumbers(int max)

{

    int i = 0;

 

    int dispctr = 0;

 

 

    printf("All the prime numbers under %d are given below:\n". max);

    for(i = 2; i <= max; i++)

    {

      if(IsPrimeNumber(i) == 1)

Page 98: C Programming With Solutions

      {

          printf("%d\t", i);

          dispctr = dispctr + 1;

 

 

          if(dispctr >= 6)

          {

            printf("\n");

            dispctr = 0;

          }

      }

    }

    printf("\n");

}

 

int main()

{

      GeneratePrimeNumbers(1000);

      return 0;

}

Output

All the prime numbers under 1000 are given below:

2   3   5   7   11  13 

17  19  23  29  31  37 

41  43  47  53  59  61 

67  71  73  79  83  89 

97  101 103 107 109 113 

127 131 137 139 149 151 

157 163 167 173 179 181 

191 193 197 199 211 223 

227 229 233 239 241 251 

257 263 269 271 277 281 

283 293 307 311 313 317 

331 337 347 349 353 359 

367 373 379 383 389 397 

401 409 419 421 431 433 

439 443 449 457 461 463 

467 479 487 491 499 503 

Page 99: C Programming With Solutions

509 521 523 541 547 557 

563 569 571 577 587 593 

599 601 607 613 617 619 

631 641 643 647 653 659 

661 673 677 683 691 701 

709 719 727 733 739 743 

751 757 761 769 773 787 

797 809 811 821 823 827 

829 839 853 857 859 863 

877 881 883 887 907 911 

919 929 937 941 947 953 

967 971 977 983 991 997 

18. Getting Prime Factors of a Number

Source Code

#include <stdio.h>

 

 

#define MAX_SIZE 15000

 

enum bool

{

      false = 0, true = 1

};

 

bool IsPrimeNumber(long num)

{

    bool bPrime = true;

    long factor = num / 2;

    long i = 0;

 

    for(i = 2; i <= factor; i++)

    {

      if( (num % i) == 0)

          bPrime = false;

    }

    return bPrime;

}

Page 100: C Programming With Solutions

 

long GetPrimeFactors(long num, long *arrResult)

{

    long count = 0;

    long arr[MAX_SIZE];

 

    long i = 0;

 

    long idx = 0;

 

    for(i = 2; i <= num; i++)

    {

      if(IsPrimeNumber(i) == true)

          arr[count++] = i;

    }

 

    while(1)

    {

      if(IsPrimeNumber(num) == true)

      {

          arrResult[idx++] = num;

          break;

      }

      for(i = count - 1; i >= 0; i--)

      {

          if( (num % arr[i]) == 0)

          {

            arrResult[idx++] = arr[i];

            num = num / arr[i];

            break;

          }

      }

    }

    return idx;

}

 

long main()

{

    long num1;

Page 101: C Programming With Solutions

    long result[MAX_SIZE];

 

    long count =  0;

    int i = 0;

 

 

    printf("Enter a Number: ");

    scanf("%d", &num1);

 

    count = GetPrimeFactors(num1, result);

 

    printf("Prime Factor For %d = ", num1);

 

 

    for(i = 0; i < count; i++)

    {

      printf("%d", result[i]);

      if(i != count - 1)

            printf(" * ");

    }

    printf("\n");

 

    return 0;

}

Output

Enter a Number: 9360

Prime Factors For 9360 = 13 *  5 *  3 *  3 *  2 *  2 *  2 *  2

Press any key to continue . . .

 

Enter a Number: 48125

Prime Factors For 48125 = 11 *  7 *  5 *  5 *  5 *  5

Press any key to continue . . .

Prime Factor For 9360 = 13 *  5 *  3 *  3 *  2 *  2 *  2 *  2

Page 102: C Programming With Solutions

19. Calculate Mean

Source Code

#include <stdlib.h>#include <stdio.h>#include <math.h>   float CalculateMean(float *value, int max){    int i;    float sum = 0;     for( i = 0; i < max; i++)      sum = sum + value[i];    return (sum / max);}  int main(){     float arrNumbers[100];    int i, max;    float mean;    char buf[1024];      printf("Total Number of Elements: ");    scanf("%d", &max);     for(i = 0; i < max; i++)    {       printf("Enter [%d] Number: ", i + 1);       scanf("%f", &arrNumbers[i]);    }     printf("Total Numbers: %d\n", max);     mean = CalculateMean(arrNumbers, max);     printf("Mean: %f", mean);     return 0;}

Output

Total Number of Elements: 10Enter [1] Number: 6Enter [2] Number: 7Enter [3] Number: 8

Page 103: C Programming With Solutions

Enter [4] Number: 7Enter [5] Number: 6Enter [6] Number: 5Enter [7] Number: 2Enter [8] Number: 2Enter [9] Number: 9Enter [10] Number: 3 Total Numbers: 10 Mean: 5.500000

20. Calculate Median

Source Code

#include <stdlib.h>#include <stdio.h>#include <math.h>   float CalculateMedian(float *arrValue, int max){    float median = 0;    float value[100];    int i, j;    float temp;    if(max > 100)        return 0;    for(i = 0; i < max; i++)        value[i] = arrValue[i];    for(i = 0; i < max; i++)    {                   for(j = 0; j < max - i - 1; j++)        {                if(value[j] > value[j + 1])                {                    temp = value[j];                    value[j] = value[j + 1];                    value[j + 1] = temp;                }        }    }    if( (max % 2) == 1)    {        median =  value[ (max + 1) / 2 - 1];    }    else    {        median = (value[max / 2] + value[max / 2 - 1]) / 2;    }    return median;}  

Page 104: C Programming With Solutions

 int main(){    float arrNumbers[100];    int i, max;    float median;    char buf[1024];     printf("Total Number of Elements: ");    scanf("%d", &max);     for(i = 0; i < max; i++)    {       printf("Enter [%d] Number: ", i + 1);       scanf("%f", &arrNumbers[i]);    }     printf("Total Numbers: %d\n", max);     median = CalculateMedian(arrNumbers, max);     printf("Median: %f", median);           return 0;}  

Output

Total Number of Elements: 10Enter [1] Number: 6Enter [2] Number: 7Enter [3] Number: 8Enter [4] Number: 7Enter [5] Number: 6Enter [6] Number: 5Enter [7] Number: 2Enter [8] Number: 2Enter [9] Number: 9Enter [10] Number: 3 Total Numbers: 10 Median: 6.000000 

21. Calculate Range

Source Code

#include <stdlib.h>#include <stdio.h>

Page 105: C Programming With Solutions

#include <math.h>   const char* CalculateRange(float *arrValue, int max){    static char range[128];    int i, small, big;    small = big = arrValue[0];    for(i = 0; i < max; i++)    {                   if(arrValue[i] > big)            big = arrValue[i];        if(arrValue[i] < small)            small = arrValue[i];    }       sprintf(range, "%d - %d", small, big);    return range;} int main(){    float arrNumbers[100];    int i, max;    const char *range;    char buf[1024];     printf("Total Number of Elements: ");    scanf("%d", &max);     for(i = 0; i < max; i++)    {       printf("Enter [%d] Number: ", i + 1);       scanf("%f", &arrNumbers[i]);    }     printf("Total Numbers: %d\n", max);     range = CalculateRange(arrNumbers, max);    printf("Range: %s", range);    return 0;} 

Output

Total Number of Elements: 10Enter [1] Number: 6Enter [2] Number: 7Enter [3] Number: 8Enter [4] Number: 7Enter [5] Number: 6Enter [6] Number: 5Enter [7] Number: 2Enter [8] Number: 2

Page 106: C Programming With Solutions

Enter [9] Number: 9Enter [10] Number: 3 Total Numbers: 10Range: 2 - 9

21. Calculate Mode

Source Code

#include <stdlib.h>#include <stdio.h>#include <math.h>  typedef struct _Pair{    int key;    int value;} Pair; typedef struct _Collection{    Pair m_pair[100];    int m_maxElements;} Collection; const char* CalculateMode(float *arrValue, int max){    static char mode[256] = "";    char buf[32];    float value[100];    int i, j;    int highcount = 0;    float temp;    int nIndex = -1;    Collection map;    Pair ptemp;     memset(map.m_pair, 0, sizeof(Pair) * 100);    map.m_maxElements = 0;     if(max > 100)        return 0;     for(i = 0; i < max; i++)        value[i] = arrValue[i];    for(i = 0; i < max; i++)    {                   for(j = 0; j < max - i - 1; j++)        {                if(value[j] > value[j + 1])                {                    temp = value[j];                    value[j] = value[j + 1];                    value[j + 1] = temp;

Page 107: C Programming With Solutions

                }        }    }     for(i = 0; i < max; i++)    {        // Insert arrValue[i] to the map        nIndex = -1;        for(j = 0; j < map.m_maxElements; j++)        {            if(map.m_pair[j].key == value[i])            {                nIndex = j;                break;            }        }        if(nIndex == -1)        {            map.m_pair[map.m_maxElements].key = value[i];            map.m_pair[map.m_maxElements].value = 1;            map.m_maxElements++;        }        else        {            // map.m_pair[nIndex].key = value[i]; // alreday written            map.m_pair[nIndex].value++;        }    }       for(i = 0; i < map.m_maxElements; i++)    {                   for(j = 0; j < map.m_maxElements - i - 1; j++)        {            if(map.m_pair[j].value < map.m_pair[j + 1].value)                {                ptemp = map.m_pair[j];                    map.m_pair[j] = map.m_pair[j + 1];                    map.m_pair[j + 1] = ptemp;                }        }    }     highcount = map.m_pair[0].value;     for(i = 0; i < map.m_maxElements; i++)    {        if(highcount == map.m_pair[i].value)        {            sprintf(buf, "%d ", map.m_pair[i].key);            strcat(mode, buf);        }        //std::cout << map.m_pair[i].key << " " << map.m_pair[i].value << "\n";    }     return mode;}

Page 108: C Programming With Solutions

  int main(){    float arrNumbers[100];    int i, max;    float mean;    const char *mode;    char buf[1024];     printf("Total Number of Elements: ");    scanf("%d", &max);     for(i = 0; i < max; i++)    {       printf("Enter [%d] Number: ", i + 1);       scanf("%f", &arrNumbers[i]);    }     printf("Total Numbers: %d\n", max);     mode = CalculateMode(arrNumbers, max);     printf("Mode: %s", mode);    return 0;} 

Output

Total Number of Elements: 10Enter [1] Number: 6Enter [2] Number: 7Enter [3] Number: 8Enter [4] Number: 7Enter [5] Number: 6Enter [6] Number: 5Enter [7] Number: 2Enter [8] Number: 2Enter [9] Number: 9Enter [10] Number: 3 Total Numbers: 10 Mode: 2 6 7

22. Calculate Variance

Source Code

#include <stdlib.h>#include <stdio.h>#include <math.h>  

Page 109: C Programming With Solutions

typedef struct _Pair{    int key;    int value;} Pair; typedef struct _Collection{    Pair m_pair[100];    int m_maxElements;} Collection; const char* CalculateMode(float *arrValue, int max){    static char mode[256] = "";    char buf[32];    float value[100];    int i, j;    int highcount = 0;    float temp;    int nIndex = -1;    Collection map;    Pair ptemp;     memset(map.m_pair, 0, sizeof(Pair) * 100);    map.m_maxElements = 0;     if(max > 100)        return 0;     for(i = 0; i < max; i++)        value[i] = arrValue[i];    for(i = 0; i < max; i++)    {                   for(j = 0; j < max - i - 1; j++)        {                if(value[j] > value[j + 1])                {                    temp = value[j];                    value[j] = value[j + 1];                    value[j + 1] = temp;                }        }    }     for(i = 0; i < max; i++)    {        // Insert arrValue[i] to the map        nIndex = -1;        for(j = 0; j < map.m_maxElements; j++)        {            if(map.m_pair[j].key == value[i])            {                nIndex = j;                break;            }        }

Page 110: C Programming With Solutions

        if(nIndex == -1)        {            map.m_pair[map.m_maxElements].key = value[i];            map.m_pair[map.m_maxElements].value = 1;            map.m_maxElements++;        }        else        {            // map.m_pair[nIndex].key = value[i]; // alreday written            map.m_pair[nIndex].value++;        }    }       for(i = 0; i < map.m_maxElements; i++)    {                   for(j = 0; j < map.m_maxElements - i - 1; j++)        {            if(map.m_pair[j].value < map.m_pair[j + 1].value)                {                ptemp = map.m_pair[j];                    map.m_pair[j] = map.m_pair[j + 1];                    map.m_pair[j + 1] = ptemp;                }        }    }     highcount = map.m_pair[0].value;     for(i = 0; i < map.m_maxElements; i++)    {        if(highcount == map.m_pair[i].value)        {            sprintf(buf, "%d ", map.m_pair[i].key);            strcat(mode, buf);        }        //std::cout << map.m_pair[i].key << " " << map.m_pair[i].value << "\n";    }     return mode;}  int main(){    float arrNumbers[100];    int i, max;    float mean;    const char *mode;    char buf[1024];     printf("Total Number of Elements: ");    scanf("%d", &max);     for(i = 0; i < max; i++)    {       printf("Enter [%d] Number: ", i + 1);

Page 111: C Programming With Solutions

       scanf("%f", &arrNumbers[i]);    }     printf("Total Numbers: %d\n", max);     mode = CalculateMode(arrNumbers, max);     printf("Mode: %s", mode);    return 0;} 

Output

Total Number of Elements: 10Enter [1] Number: 6Enter [2] Number: 7Enter [3] Number: 8Enter [4] Number: 7Enter [5] Number: 6Enter [6] Number: 5Enter [7] Number: 2Enter [8] Number: 2Enter [9] Number: 9Enter [10] Number: 3 Total Numbers: 10 Mode: 2 6 7

23. Calculate Sample and Population Standard Deviation

Source Code

#include <stdlib.h>#include <stdio.h>#include <math.h>  typedef struct _Pair{    int key;    int value;} Pair; typedef struct _Collection{    Pair m_pair[100];    int m_maxElements;} Collection; const char* CalculateMode(float *arrValue, int max){    static char mode[256] = "";

Page 112: C Programming With Solutions

    char buf[32];    float value[100];    int i, j;    int highcount = 0;    float temp;    int nIndex = -1;    Collection map;    Pair ptemp;     memset(map.m_pair, 0, sizeof(Pair) * 100);    map.m_maxElements = 0;     if(max > 100)        return 0;     for(i = 0; i < max; i++)        value[i] = arrValue[i];    for(i = 0; i < max; i++)    {                   for(j = 0; j < max - i - 1; j++)        {                if(value[j] > value[j + 1])                {                    temp = value[j];                    value[j] = value[j + 1];                    value[j + 1] = temp;                }        }    }     for(i = 0; i < max; i++)    {        // Insert arrValue[i] to the map        nIndex = -1;        for(j = 0; j < map.m_maxElements; j++)        {            if(map.m_pair[j].key == value[i])            {                nIndex = j;                break;            }        }        if(nIndex == -1)        {            map.m_pair[map.m_maxElements].key = value[i];            map.m_pair[map.m_maxElements].value = 1;            map.m_maxElements++;        }        else        {            // map.m_pair[nIndex].key = value[i]; // alreday written            map.m_pair[nIndex].value++;        }    }       for(i = 0; i < map.m_maxElements; i++)    {           

Page 113: C Programming With Solutions

        for(j = 0; j < map.m_maxElements - i - 1; j++)        {            if(map.m_pair[j].value < map.m_pair[j + 1].value)                {                ptemp = map.m_pair[j];                    map.m_pair[j] = map.m_pair[j + 1];                    map.m_pair[j + 1] = ptemp;                }        }    }     highcount = map.m_pair[0].value;     for(i = 0; i < map.m_maxElements; i++)    {        if(highcount == map.m_pair[i].value)        {            sprintf(buf, "%d ", map.m_pair[i].key);            strcat(mode, buf);        }        //std::cout << map.m_pair[i].key << " " << map.m_pair[i].value << "\n";    }     return mode;}   float CalculateMedian(float *arrValue, int max){    float median = 0;    float value[100];    int i, j;    float temp;    if(max > 100)        return 0;    for(i = 0; i < max; i++)        value[i] = arrValue[i];    for(i = 0; i < max; i++)    {                   for(j = 0; j < max - i - 1; j++)        {                if(value[j] > value[j + 1])                {                    temp = value[j];                    value[j] = value[j + 1];                    value[j + 1] = temp;                }        }    }    if( (max % 2) == 1)    {        median =  value[ (max + 1) / 2 - 1];    }    else    {

Page 114: C Programming With Solutions

        median = (value[max / 2] + value[max / 2 - 1]) / 2;    }    return median;} const char* CalculateRange(float *arrValue, int max){    static char range[128];    int i, small, big;    small = big = arrValue[0];    for(i = 0; i < max; i++)    {                   if(arrValue[i] > big)            big = arrValue[i];        if(arrValue[i] < small)            small = arrValue[i];    }       sprintf(range, "%d - %d", small, big);    return range;}     float CalculateMean(float *value, int max){    int i;    float sum = 0;     for( i = 0; i < max; i++)        sum = sum + value[i];    return (sum / max);}   float CalculateVariane(float *value, int max){    float mean = CalculateMean(value, max);    int i = 0;    float temp = 0;     for(i = 0; i < max; i++)         temp += (value[i] - mean) * (value[i] - mean) ;     return temp / max;} float CalculateSampleVariane(float *value, int max){    float mean = CalculateMean(value, max);    float temp = 0;    int i = 0;     for(i = 0; i < max; i++)

Page 115: C Programming With Solutions

         temp += (value[i] - mean) * (value[i] - mean) ;     return temp / (max - 1);}   float GetStandardDeviation(float *value, int max){    return sqrt(CalculateVariane(value, max));}  float GetSampleStandardDeviation(float *value, int max){    return sqrt(CalculateSampleVariane(value, max));} int main(){    float arrNumbers[100];    int i, max;    float mean, devi, sampledevi;    float median;    const char *mode, *range;    char buf[1024];    float variance, samplevariance;      printf("Total Number of Elements: ");    scanf("%d", &max);     for(i = 0; i < max; i++)    {       printf("Enter [%d] Number: ", i + 1);       scanf("%f", &arrNumbers[i]);    }     printf("\nTotal Numbers: %d", max);     mean = CalculateMean(arrNumbers, max);    mode = CalculateMode(arrNumbers, max);    median = CalculateMedian(arrNumbers, max);    range = CalculateRange(arrNumbers, max);    variance = CalculateVariane(arrNumbers, max);    samplevariance = CalculateSampleVariane(arrNumbers, max);    devi = GetStandardDeviation(arrNumbers, max);    sampledevi = GetSampleStandardDeviation(arrNumbers, max);     printf("\nMean: %f", mean);    printf("\nMedian: %f", median);    printf("\nMode: %s", mode);    printf("\nRange: %s", range);    printf("\nSample Variance: %f", samplevariance);    printf("\nPopulation Variance: %f",  variance);    printf("\nSample Stdandrd Deviation: %f", sampledevi);    printf("\nPopulation Standard Deviation: %f", devi);

Page 116: C Programming With Solutions

     return 0;}

  

Output

Total Number of Elements: 10Enter [1] Number: 6Enter [2] Number: 7Enter [3] Number: 8Enter [4] Number: 7Enter [5] Number: 6Enter [6] Number: 5Enter [7] Number: 2Enter [8] Number: 2Enter [9] Number: 9Enter [10] Number: 3 Total Numbers: 10 Mean: 5.500000Median: 6.000000Mode: 2 6 7Range: 2 - 9Sample Variance: 6.055555Population Variance: 5.450000Sample Stdandrd Deviation: 2.460804Population Standard Deviation: 2.334523

24. Greatest Common Divisor (GCD) and Least Common Multiple (LCM)

Source Code

#include <stdio.h>  int GetGCD(int num1, int num2){       while(num1!=num2)       {       if(num1 > num2)              num1 = num1 - num2;       if(num2 > num1)              num2 = num2 - num1;       }       return num1;} int GetLCM(int num1, long num2){

Page 117: C Programming With Solutions

    return (num1 * num2) / GetGCD(num1, num2);} long main(){    long num1, num2;    long gcd, lcm;     printf("Enter First Number: ");    scanf("%d", &num1);     printf("Enter Second Number: ");    scanf("%d", &num2);     gcd = GetGCD(num1, num2);    lcm = GetLCM(num1, num2);     printf("\nGCD(%d,%d) = %d\n", num1, num2, gcd);    printf("\nLCM(%d,%d) = %d\n\n\n", num1, num2, lcm);     return 0;} 

Output

 Enter First Number: 10Enter Second Number: 135 GCD(10,135) = 5LCM(10,135) = 270  Press any key to continue . . . 

25. Using Sine Series to find Sin Value

Source Code

#include <math.h>#include <stdio.h> const double PI = 3.14159265; // sin series = x - x^3/3! + x^5/5! - x^7 / 7!double MySin(double x){    double sqx = x * x * x;     double sineresult = x;    double fact = 2 * 3;    int index = 3;    int term = 0;

Page 118: C Programming With Solutions

    double termfactor = 0;     for(term = 1; term < 20; term++)    {        termfactor = 0;        termfactor = sqx / fact;        if(term % 2)        {            sineresult = sineresult - termfactor;        }        else        {            sineresult = sineresult + termfactor;        }        index++;        fact *= index;        index++;        fact *= index;        sqx *= (x*x);    }     return sineresult;}

  int main(){        double i = 0;        for(i = 0; i <= 360; i += 4.75)        {        printf("%.4lf = %.4lf\t%.4lf\n", i,                        sin(i * PI / 180), MySin(i * PI / 180));           //printf("%.4lf\n", sin(i * PI / 180) - MySin(i * PI / 180));    }    return 0;}

Output

0.0000  = 0.0000        0.00004.7500  = 0.0828        0.08289.5000  = 0.1650        0.165014.2500 = 0.2462        0.246219.0000 = 0.3256        0.325623.7500 = 0.4027        0.402728.5000 = 0.4772        0.477233.2500 = 0.5483        0.548338.0000 = 0.6157        0.615742.7500 = 0.6788        0.678847.5000 = 0.7373        0.737352.2500 = 0.7907        0.790757.0000 = 0.8387        0.838761.7500 = 0.8809        0.880966.5000 = 0.9171        0.917171.2500 = 0.9469        0.946976.0000 = 0.9703        0.9703

Page 119: C Programming With Solutions

80.7500 = 0.9870        0.987085.5000 = 0.9969        0.996990.2500 = 1.0000        1.000095.0000 = 0.9962        0.996299.7500 = 0.9856        0.9856104.5000 = 0.9681       0.9681109.2500 = 0.9441       0.9441114.0000 = 0.9135       0.9135118.7500 = 0.8767       0.8767123.5000 = 0.8339       0.8339128.2500 = 0.7853       0.7853133.0000 = 0.7314       0.7314137.7500 = 0.6724       0.6724142.5000 = 0.6088       0.6088147.2500 = 0.5410       0.5410152.0000 = 0.4695       0.4695156.7500 = 0.3947       0.3947161.5000 = 0.3173       0.3173166.2500 = 0.2377       0.2377171.0000 = 0.1564       0.1564175.7500 = 0.0741       0.0741180.5000 = -0.0087      -0.0087185.2500 = -0.0915      -0.0915190.0000 = -0.1736      -0.1736194.7500 = -0.2546      -0.2546199.5000 = -0.3338      -0.3338204.2500 = -0.4107      -0.4107209.0000 = -0.4848      -0.4848213.7500 = -0.5556      -0.5556218.5000 = -0.6225      -0.6225223.2500 = -0.6852      -0.6852228.0000 = -0.7431      -0.7431232.7500 = -0.7960      -0.7960237.5000 = -0.8434      -0.8434242.2500 = -0.8850      -0.8850247.0000 = -0.9205      -0.9205251.7500 = -0.9497      -0.9497256.5000 = -0.9724      -0.9724261.2500 = -0.9884      -0.9884266.0000 = -0.9976      -0.9976270.7500 = -0.9999      -0.9999275.5000 = -0.9954      -0.9954280.2500 = -0.9840      -0.9840285.0000 = -0.9659      -0.9659289.7500 = -0.9412      -0.9412294.5000 = -0.9100      -0.9100299.2500 = -0.8725      -0.8725304.0000 = -0.8290      -0.8290308.7500 = -0.7799      -0.7799313.5000 = -0.7254      -0.7254318.2500 = -0.6659      -0.6659323.0000 = -0.6018      -0.6018327.7500 = -0.5336      -0.5336332.5000 = -0.4617      -0.4617337.2500 = -0.3867      -0.3867342.0000 = -0.3090      -0.3090346.7500 = -0.2292      -0.2292

Page 120: C Programming With Solutions

351.5000 = -0.1478      -0.1478356.2500 = -0.0654      -0.0654Press any key to continue . . .

26. Using Cosine Series to find COS ValueCosine series = 1 - x^2/2! + x^4/4! - x^6 / 6! + x^8 / 8! - .....

Source Code

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

const double PI = 3.14159265; // cos series = 1 - x^2/2! + x^4/4! - x^6 / 6!double MyCos(double x){    double sqx = x * x;     double cosineresult = 1;    double fact = 2;    int index = 2;    int term = 0;    double termfactor = 0;     for(term = 1; term < 20; term++)    {        termfactor = 0;        termfactor = sqx / fact;        if(term %2)        {            cosineresult = cosineresult - termfactor;        }        else        {            cosineresult = cosineresult + termfactor;        }        index++;        fact *= index;        index++;        fact *= index;        sqx *= (x*x);    }    return cosineresult;

}  int main(){    double i = 0;    for(i = 0; i <= 360; i += 4.75)    {        printf("%.4lf = %.4lf\t%.4lf\n", i, cos(i * PI / 180), MyCos(i * PI / 180));        //printf("%.4lf\n", cos(i * PI / 180) - MyCos(i * PI / 180));    }    return 0;}

Page 121: C Programming With Solutions

Output

0.0000  = 1.0000            1.0000

4.7500  = 0.9966            0.9966

9.5000  = 0.9863            0.9863

14.2500 = 0.9692        0.9692

19.0000 = 0.9455        0.9455

23.7500 = 0.9153        0.9153

28.5000 = 0.8788        0.8788

33.2500 = 0.8363        0.8363

38.0000 = 0.7880        0.7880

42.7500 = 0.7343        0.7343

47.5000 = 0.6756        0.6756

52.2500 = 0.6122        0.6122

57.0000 = 0.5446        0.5446

61.7500 = 0.4733        0.4733

66.5000 = 0.3987        0.3987

71.2500 = 0.3214        0.3214

76.0000 = 0.2419        0.2419

80.7500 = 0.1607        0.1607

85.5000 = 0.0785        0.0785

90.2500 = -0.0044       -0.0044

95.0000 = -0.0872       -0.0872

99.7500 = -0.1693       -0.1693

104.5000 = -0.2504      -0.2504

109.2500 = -0.3297      -0.3297

114.0000 = -0.4067      -0.4067

118.7500 = -0.4810      -0.4810

123.5000 = -0.5519      -0.5519

128.2500 = -0.6191      -0.6191

133.0000 = -0.6820      -0.6820

137.7500 = -0.7402      -0.7402

142.5000 = -0.7934      -0.7934

147.2500 = -0.8410      -0.8410

152.0000 = -0.8829      -0.8829

156.7500 = -0.9188      -0.9188

161.5000 = -0.9483      -0.9483

166.2500 = -0.9713      -0.9713

171.0000 = -0.9877      -0.9877

Page 122: C Programming With Solutions

175.7500 = -0.9973      -0.9973

180.5000 = -1.0000      -1.0000

185.2500 = -0.9958      -0.9958

190.0000 = -0.9848      -0.9848

194.7500 = -0.9670      -0.9670

199.5000 = -0.9426      -0.9426

204.2500 = -0.9118      -0.9118

209.0000 = -0.8746      -0.8746

213.7500 = -0.8315      -0.8315

218.5000 = -0.7826      -0.7826

223.2500 = -0.7284      -0.7284

228.0000 = -0.6691      -0.6691

232.7500 = -0.6053      -0.6053

237.5000 = -0.5373      -0.5373

242.2500 = -0.4656      -0.4656

247.0000 = -0.3907      -0.3907

251.7500 = -0.3132      -0.3132

256.5000 = -0.2334      -0.2334

261.2500 = -0.1521      -0.1521

266.0000 = -0.0698      -0.0698

270.7500 = 0.0131       0.0131

275.5000 = 0.0958       0.0958

280.2500 = 0.1779       0.1779

285.0000 = 0.2588       0.2588

289.7500 = 0.3379       0.3379

294.5000 = 0.4147       0.4147

299.2500 = 0.4886       0.4886

304.0000 = 0.5592       0.5592

308.7500 = 0.6259       0.6259

313.5000 = 0.6884       0.6884

318.2500 = 0.7461       0.7461

323.0000 = 0.7986       0.7986

327.7500 = 0.8457       0.8457

332.5000 = 0.8870       0.8870

337.2500 = 0.9222       0.9222

342.0000 = 0.9511       0.9511

346.7500 = 0.9734       0.9734

351.5000 = 0.9890       0.9890

356.2500 = 0.9979       0.9979

Page 123: C Programming With Solutions

Press any key to continue . . .

27. Using Sine and Cosine Series to find TAN Valuesine series = x - x^3/3! + x^5/5! - x^7 / 7! + x^9 / 9! - .......

cosine series = 1 - x^2/2! + x^4/4! - x^6 / 6! + X^8 / 8! - ....

Tan Series = sine series / cosine series

Source Code

#include <math.h>#include <stdio.h> const double PI = 3.14159265;

 // tan series = sine series / cosine seriesdouble MyTan(double x){    double sineresult = x;    double cosineresult = 1;    double sqx = 0;    double fact = 0;    int index = 0;    int term = 0;    double termfactor = 0;     {        sqx = x * x * x;        fact = 2 * 3;        index = 3;         for(term = 1; term < 20; term++)        {            termfactor = 0;            termfactor = sqx / fact;            if(term % 2)            {                sineresult = sineresult - termfactor;            }            else            {                sineresult = sineresult + termfactor;            }            index++;            fact *= index;            index++;            fact *= index;            sqx *= (x*x);        }    }    {        sqx = x * x;        fact = 2;        index = 2;

Page 124: C Programming With Solutions

         for(term = 1; term < 20; term++)        {            termfactor = 0;            termfactor = sqx / fact;            if(term %2)            {                cosineresult = cosineresult - termfactor;            }            else            {                cosineresult = cosineresult + termfactor;            }            index++;            fact *= index;            index++;            fact *= index;            sqx *= (x*x);        }    }    return sineresult / cosineresult;} int main(){    double i = 0;    for(i = 0; i <= 360; i += 4.75)    {        printf("%.4lf = %.4lf\t%.4lf\n", i,            tan(i * PI / 180), MyTan(i * PI / 180));        //printf("%.4lf\n", tan(i * PI / 180) - MyTan(i * PI / 180));     }     return 0;}

 

Output

0.0000 = 0.0000 0.00004.7500 = 0.0831 0.08319.5000 = 0.1673 0.167314.2500 = 0.2540        0.254019.0000 = 0.3443        0.344323.7500 = 0.4400        0.440028.5000 = 0.5430        0.543033.2500 = 0.6556        0.655638.0000 = 0.7813        0.781342.7500 = 0.9244        0.924447.5000 = 1.0913        1.091352.2500 = 1.2915        1.291557.0000 = 1.5399        1.539961.7500 = 1.8611        1.8611

Page 125: C Programming With Solutions

66.5000 = 2.2998        2.299871.2500 = 2.9459        2.945976.0000 = 4.0108        4.010880.7500 = 6.1402        6.140285.5000 = 12.7062       12.706290.2500 = -229.1818     -229.181895.0000 = -11.4301      -11.430199.7500 = -5.8197       -5.8197104.5000 = -3.8667      -3.8667109.2500 = -2.8636      -2.8636114.0000 = -2.2460      -2.2460118.7500 = -1.8228      -1.8228123.5000 = -1.5108      -1.5108128.2500 = -1.2685      -1.2685133.0000 = -1.0724      -1.0724137.7500 = -0.9083      -0.9083142.5000 = -0.7673      -0.7673147.2500 = -0.6432      -0.6432152.0000 = -0.5317      -0.5317156.7500 = -0.4296      -0.4296161.5000 = -0.3346      -0.3346166.2500 = -0.2447      -0.2447171.0000 = -0.1584      -0.1584175.7500 = -0.0743      -0.0743180.5000 = 0.0087       0.0087185.2500 = 0.0919       0.0919190.0000 = 0.1763       0.1763194.7500 = 0.2633       0.2633199.5000 = 0.3541       0.3541204.2500 = 0.4505       0.4505209.0000 = 0.5543       0.5543213.7500 = 0.6682       0.6682218.5000 = 0.7954       0.7954223.2500 = 0.9407       0.9407228.0000 = 1.1106       1.1106232.7500 = 1.3151       1.3151237.5000 = 1.5697       1.5697242.2500 = 1.9007       1.9007247.0000 = 2.3559       2.3559251.7500 = 3.0326       3.0326256.5000 = 4.1653       4.1653261.2500 = 6.4971       6.4971266.0000 = 14.3007      14.3007270.7500 = -76.3900     -76.3900275.5000 = -10.3854     -10.3854280.2500 = -5.5301      -5.5301285.0000 = -3.7321      -3.7321289.7500 = -2.7852      -2.7852294.5000 = -2.1943      -2.1943299.2500 = -1.7856      -1.7856

Page 126: C Programming With Solutions

304.0000 = -1.4826      -1.4826308.7500 = -1.2460      -1.2460313.5000 = -1.0538      -1.0538318.2500 = -0.8925      -0.8925323.0000 = -0.7536      -0.7536327.7500 = -0.6310      -0.6310332.5000 = -0.5206      -0.5206337.2500 = -0.4193      -0.4193342.0000 = -0.3249      -0.3249346.7500 = -0.2355      -0.2355351.5000 = -0.1495      -0.1495356.2500 = -0.0655      -0.0655Press any key to continue . . .

28. Quadratic Equation Solver - ax2 + bx + c = 0x = [ -b +/- sqrt(b^2 - 4ac) ] / 2a

We have to find the value of (b*b - 4*a*c). 

1. When it is greater than Zero, we will get two Real Solutions.2. When it is equal to zero, we will get one Real Solution.3. When it is less than Zero, we will get two Imaginary Solutions.

When there is an imaginary solutions, we have to use the factor i to represent imaginary part as it is a complex number.

Source Code

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

 // quadratic equation is a second order of polynomial equation in a single variable // x = [ -b +/- sqrt(b^2 - 4ac) ] / 2avoid SolveQuadratic(double a, double b, double c){    double sqrtpart = b*b - 4*a*c;    double x, x1, x2, img;    if(sqrtpart > 0)    {        x1 = (-b + sqrt(sqrtpart)) / (2 * a);        x2 = (-b - sqrt(sqrtpart)) / (2 * a);        printf("Two Real Solutions: %.4lf or %.4lf\n\n", x1, x2);    }    else if(sqrtpart < 0)    {        sqrtpart = -sqrtpart;        x = -b / (2 * a);        img = sqrt(sqrtpart) / (2 * a);        printf("Two Imaginary Solutions: %.4lf + %.4lf i or %.4lf + %.4lf i\n\n", x, img, x, img);    }    else

Page 127: C Programming With Solutions

    {        x = (-b + sqrt(sqrtpart)) / (2 * a);        printf("One Real Solution: %.4lf\n\n", x);    }} int main(){    // 6x^2 + 11x - 35 = 0    SolveQuadratic(6, 11, -35);

// 5x^2 + 6x + 1 = 0    SolveQuadratic(5, 6, 1);

// 2x^2 + 4x + 2 = 0    SolveQuadratic(2, 4, 2);

// 5x^2 + 2x + 1 = 0SolveQuadratic(5, 2, 1);           return 0;}    

Output

Two Real Solutions: 1.6667 or -3.5000

 

Two Real Solutions: -0.2000 or -1.0000

 

One Real Solution: -1.0000

 

Two Imaginary Solutions: -0.2000 + 0.4000 i or -0.2000 + 0.4000 i

 

Press any key to continue . . .

29.  Using Exponent Series and Eulers Number to find EXP Valueexp(x) series = 1 + x + x^2 / 2! + x^3 / 3! + x^4 / 4! + x^5 / %! + .....

exp(x) series = power(2.71828, x)

Source Code

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

Page 128: C Programming With Solutions

 const double PI = 3.14159265;const double EulersNumber = 2.71828;  // exp(x) series = 1 + x + x^2 / 2! + x^3 / 3! + x^4 / 4!double MyExp1(double x){    double f = x;    double result = 1 + x;    double fact = 1;    int i = 0;    for(i = 2; i < 20; i++)    {        fact *= i;        f *= x;        result += f / fact;       }    return result;} // exp(x) series = power(2.71828, x)double MyExp2(double x){    return pow(EulersNumber, x);} int main(){    double i;    for( i = -2; i <= 3; i += 0.1)    {        printf("%.4lf  =  %.4lf  %.4lf  %.4lf\n",                i, exp(i), MyExp1(i), MyExp2(i) );    }    return 0;}

Output

-2.0000  =  0.1353  0.1353  0.1353-1.9000  =  0.1496  0.1496  0.1496-1.8000  =  0.1653  0.1653  0.1653-1.7000  =  0.1827  0.1827  0.1827-1.6000  =  0.2019  0.2019  0.2019-1.5000  =  0.2231  0.2231  0.2231-1.4000  =  0.2466  0.2466  0.2466-1.3000  =  0.2725  0.2725  0.2725-1.2000  =  0.3012  0.3012  0.3012-1.1000  =  0.3329  0.3329  0.3329-1.0000  =  0.3679  0.3679  0.3679-0.9000  =  0.4066  0.4066  0.4066-0.8000  =  0.4493  0.4493  0.4493-0.7000  =  0.4966  0.4966  0.4966-0.6000  =  0.5488  0.5488  0.5488-0.5000  =  0.6065  0.6065  0.6065-0.4000  =  0.6703  0.6703  0.6703

Page 129: C Programming With Solutions

-0.3000  =  0.7408  0.7408  0.7408-0.2000  =  0.8187  0.8187  0.8187-0.1000  =  0.9048  0.9048  0.90480.0000  =  1.0000  1.0000  1.00000.1000  =  1.1052  1.1052  1.10520.2000  =  1.2214  1.2214  1.22140.3000  =  1.3499  1.3499  1.34990.4000  =  1.4918  1.4918  1.49180.5000  =  1.6487  1.6487  1.64870.6000  =  1.8221  1.8221  1.82210.7000  =  2.0138  2.0138  2.01380.8000  =  2.2255  2.2255  2.22550.9000  =  2.4596  2.4596  2.45961.0000  =  2.7183  2.7183  2.71831.1000  =  3.0042  3.0042  3.00421.2000  =  3.3201  3.3201  3.32011.3000  =  3.6693  3.6693  3.66931.4000  =  4.0552  4.0552  4.05521.5000  =  4.4817  4.4817  4.48171.6000  =  4.9530  4.9530  4.95301.7000  =  5.4739  5.4739  5.47391.8000  =  6.0496  6.0496  6.04961.9000  =  6.6859  6.6859  6.68592.0000  =  7.3891  7.3891  7.38902.1000  =  8.1662  8.1662  8.16622.2000  =  9.0250  9.0250  9.02502.3000  =  9.9742  9.9742  9.97422.4000  =  11.0232  11.0232  11.02322.5000  =  12.1825  12.1825  12.18252.6000  =  13.4637  13.4637  13.46372.7000  =  14.8797  14.8797  14.87972.8000  =  16.4446  16.4446  16.44462.9000  =  18.1741  18.1741  18.1741Press any key to continue . . .

30. Finding the Intersection of two Lines Given Slope and Intercept of Two Lines

Source Code

#include <stdio.h>

#include <math.h>

 

void main()

{

    float m1, c1, m2, c2;

    float dx, dy;

    float intersection_X, intersection_Y;

 

    printf("Program to find the intersecting point of two lines:\n");

 

    printf("Enter Line1 - Slope: ");

Page 130: C Programming With Solutions

    scanf("%f", &m1);

 

    printf("Enter Line1 - Intercept: ");

    scanf("%f", &c1);

 

    printf("Enter Line1 - Slope: ");

    scanf("%f", &m2);

 

    printf("Enter Line1 - Intercept: ");

    scanf("%f", &c2);

 

    printf("Equation of line1: Y = %.2fX %c %.2f\n", m1, (c1 < 0) ? '

' : '+',  c1);

    printf("Equation of line2: Y = %.2fX %c %.2f\n", m2, (c2 < 0) ? '

' : '+',  c2);

 

    if( (m1 - m2) == 0)

        printf("No Intersection between the lines\n");

    else

    {

        intersection_X = (c2 - c1) / (m1 - m2);

        intersection_Y = m1 * intersection_X + c1;

        printf("Intersecting Point: = %.2f, %.2f\n", intersection_X,

intersection_Y);

    }

}

Output

 

Program to find the intersecting point of two lines:

Enter Line1 - Slope: 1.25

Enter Line1 - Intercept: 0.75

Enter Line2 - Slope: 2

Enter Line2 - Intercept: -3

Equation of line1: 1.25X +0.75

Equation of line2: 2X  -3

Intersecting Point: = 5,7

Press any key to continue . . .

Page 131: C Programming With Solutions

DATA STRUCURES AND ALGORITHMS

1. Permutation Algorithm

Source Code

 #include <stdio.h>#include <string.h> void sortchar(char *buffer, int len){    int i, j;    for(i = 1; i < len; i++)    {        for(j = 0; j < len - i; j++)        {            if(buffer[j] > buffer[j + 1])            {                char temp = buffer[j];                buffer[j] = buffer[j + 1];                buffer[j + 1] = temp;            }        }    }} int NextPermuation(char *p, int len){    int i,j,k;    int anchor, count;    char *tempptr;    char ch, newchar;     for(k = len - 1; k > 0; k--)    {      if(p[k - 1] >= p[k])          continue;      else      {          if(k <= len - 3)          {            newchar = p[k-1];            anchor = -1;            for(j = len - 1; j >= k; j--)            {                if(newchar < p[j])                {                  anchor = j;                  break;                }            }            if(anchor == -1)                return 0;

Page 132: C Programming With Solutions

            ch = p[k-1];            p[k-1] = p[anchor];            p[anchor] = ch;            // sort last remaining chars            sortchar(p+k,len - k);            return 1;          }          else          {            tempptr = &p[len-3];            count = 3;            for(i = count - 1; i > 0; i--)            {                if(tempptr[i - 1] >= tempptr[i])                  continue;                else                {                  if(i <= count - 2)                  {                      if(tempptr[i+1] > tempptr[i-1])                      {                        ch = tempptr[i+1];                        tempptr[i+1] = tempptr[i];                        tempptr[i] = tempptr[i-1];                        tempptr[i-1] = ch;                      }                      else                      {                        ch = tempptr[i-1];                        tempptr[i-1] = tempptr[i];                        tempptr[i] = tempptr[i+1];                        tempptr[i+1] = ch;                      }                  }                  else                  {                      ch = tempptr[i];                      tempptr[i] = tempptr[i-1];                      tempptr[i-1] = ch;                  }                  return 1;                }            }            return 0;          }      }    }    return 0;} int main(int argc, char* argv[]){    char buf[32];    int ret;    int count = 0;     printf("Enter a string to find permutation:");

Page 133: C Programming With Solutions

    scanf("%s", buf);    //sortchar(buf, strlen(buf));     while(1)    {      printf("%s\n", buf);      count++;      ret = NextPermuation(buf, strlen(buf));      if(ret == 0)          break;    }     printf("\n\nCount: %d\n\n\n", count);    return 0;} 

 

Output

 Enter a string to find permutation: 123123132213231312321 Count: 6Press any key to continue . . .  Enter a string to find permutation: 4123412341324213423143124321 Count: 6Press any key to continue . . .  NOTE: If you use the sortchar function after the user input, then output would be changed to give always all possible combinations: Enter a string to find permutation: 4123123412431324134214231432

Page 134: C Programming With Solutions

213421432314234124132431312431423214324134123421412341324213423143124321 Count: 24Press any key to continue . . .  

2. Tower Of Hanoi Algorithm Source Code

Source Code

  #include <stdio.h>#include <alloc.h>#include <stdlib.h>#include <string.h> typedef struct _MyStack{    int *m_data;    int m_numElements;} MyStack;  static int movecount = 0;static int countA = 0;static int countB = 0;static int countC = 0; static MyStack *A = 0;static MyStack *B = 0;static MyStack *C = 0; int push(MyStack *s, int data){      if(s->m_data == NULL) // root node      {          s->m_numElements = 1;          s->m_data = (int*) malloc(sizeof(int));      }

Page 135: C Programming With Solutions

      else      {          s->m_numElements++;          s->m_data = realloc(s->m_data, s->m_numElements * sizeof(int));          memmove(&s->m_data[1], s->m_data, (s->m_numElements - 1) * sizeof(int));      }       s->m_data[0] = data;      return 1;} int pop(MyStack *s){    int result = -1;      if(s->m_data == NULL) // root node      {            s->m_numElements = 0;            return result;      }      else      {        result = top(s);          if(s->m_numElements == 1)          {            // last item                s->m_numElements = 0;                free(s->m_data);                s->m_data = NULL;          }          else          {                s->m_numElements--;                memmove(s->m_data, &s->m_data[1], s->m_numElements * sizeof(int));                s->m_data = (int*) realloc(s->m_data, s->m_numElements * sizeof(int));          }      }      return result;} int top(MyStack *s){      if(s->m_numElements > 0)          return s->m_data[0];      return 0;} int size(MyStack *s){      return s->m_numElements;} void PrintStack(MyStack *s){

Page 136: C Programming With Solutions

    int i = 0;    printf("[");    for(i = s->m_numElements - 1; i >= 0; i--)    {        printf("%d", s->m_data[i]);    }    printf("]");} void PrintStacks(){    if (countA != A->m_numElements ||        countB != B->m_numElements ||        countC != C->m_numElements)    {        int diffA = A->m_numElements - countA;        int diffB = B->m_numElements - countB;        int diffC = C->m_numElements - countC;        if (diffA == 1)        {            if (diffB == -1)                printf("Move Disc %d From B To A", top(A));            else                printf("Move Disc %d From C To A", top(A));        }        else if (diffB == 1)        {            if (diffA == -1)                printf("Move Disc %d From A To B", top(B));            else                printf("Move Disc %d From C To B", top(B));        }        else //if (diffC == 1)        {            if (diffA == -1)                printf("Move Disc %d From A To C", top(C));            else                printf("Move Disc %d From B To C", top(C));        }        countA = A->m_numElements;        countB = B->m_numElements;        countC = C->m_numElements;        printf("\n");    }     PrintStack(A);    printf(" , ");    PrintStack(B);    printf(" , ");    PrintStack(C);    printf(" , ");} void Solve2DiscsTOH(MyStack *source, MyStack *temp, MyStack *dest){               push(temp, pop(source));    movecount++;

Page 137: C Programming With Solutions

    PrintStacks();     push(dest, pop(source));    movecount++;    PrintStacks();     push(dest, pop(temp));    movecount++;    PrintStacks();} int SolveTOH(int nDiscs, MyStack *source, MyStack *temp, MyStack *dest){    if (nDiscs <= 4)    {        if ((nDiscs % 2) == 0)        {            Solve2DiscsTOH(source, temp, dest);            nDiscs = nDiscs - 1;            if (nDiscs == 1)                return 1;             push(temp, pop(source));            movecount++;            PrintStacks();            //new source is dest, new temp is source, new dest is temp;            Solve2DiscsTOH(dest, source, temp);             push(dest, pop(source));            movecount++;            PrintStacks();            //new source is temp, new temp is source, new dest is dest;            SolveTOH(nDiscs, temp, source, dest);        }        else        {            if (nDiscs == 1)                return 0;            Solve2DiscsTOH(source, dest, temp);            nDiscs = nDiscs - 1;            push(dest, pop(source));            movecount++;            PrintStacks();            Solve2DiscsTOH(temp, source, dest);        }        return 1;    }    else if (nDiscs >= 5)    {        SolveTOH(nDiscs - 2, source, temp, dest);        push(temp, pop(source));        movecount++;        PrintStacks();        SolveTOH(nDiscs - 2, dest, source, temp);        push(dest, pop(source));        movecount++;        PrintStacks();

Page 138: C Programming With Solutions

        SolveTOH(nDiscs - 1, temp, source, dest);    }    return 1;} int main(){    int sz, i, maxdisc;    A = malloc(sizeof(MyStack));    B = malloc(sizeof(MyStack));    C = malloc(sizeof(MyStack));     while(1)    {        printf("\nEnter the number of discs (-1 to exit): ");        scanf("%d", &maxdisc);        if(maxdisc == -1)            break;        if(maxdisc < 2 || maxdisc > 9)        {            printf("Enter between 2 - 9");            continue;        }         movecount = 0;        memset((void*)A, 0, sizeof(MyStack));        memset((void*)B, 0, sizeof(MyStack));        memset((void*)C, 0, sizeof(MyStack));        for (i = maxdisc; i >= 1; i--)            push(A, i);        countA = A->m_numElements;        countB = B->m_numElements;        countC = C->m_numElements;        PrintStacks();        SolveTOH(maxdisc, A, B, C);        printf("Total Moves = %d", movecount);        free(C->m_data);    }     return 0;}  Click here to download the Turbo C Source Code and executable  

Output

Enter the number of discs (-1 to exit): 0Enter between 2 - 9  Enter the number of discs (-1 to exit): 1Enter between 2 - 9 

Page 139: C Programming With Solutions

 Enter the number of discs (-1 to exit): 2[21] , [] , [] , Move Disc 1 From A To B[2] , [1] , [] , Move Disc 2 From A To C[] , [1] , [2] , Move Disc 1 From B To C[] , [] , [21] , Total Moves = 3  Enter the number of discs (-1 to exit): 3[321] , [] , [] , Move Disc 1 From A To C[32] , [] , [1] , Move Disc 2 From A To B[3] , [2] , [1] , Move Disc 1 From C To B[3] , [21] , [] , Move Disc 3 From A To C[] , [21] , [3] , Move Disc 1 From B To A[1] , [2] , [3] , Move Disc 2 From B To C[1] , [] , [32] , Move Disc 1 From A To C[] , [] , [321] , Total Moves = 7  Enter the number of discs (-1 to exit): 4[4321] , [] , [] , Move Disc 1 From A To B[432] , [1] , [] , Move Disc 2 From A To C[43] , [1] , [2] , Move Disc 1 From B To C[43] , [] , [21] , Move Disc 3 From A To B[4] , [3] , [21] , Move Disc 1 From C To A[41] , [3] , [2] , Move Disc 2 From C To B[41] , [32] , [] , Move Disc 1 From A To B[4] , [321] , [] , Move Disc 4 From A To C[] , [321] , [4] , Move Disc 1 From B To C[] , [32] , [41] , Move Disc 2 From B To A[2] , [3] , [41] , Move Disc 1 From C To A[21] , [3] , [4] , Move Disc 3 From B To C[21] , [] , [43] , Move Disc 1 From A To B[2] , [1] , [43] , Move Disc 2 From A To C[] , [1] , [432] , Move Disc 1 From B To C[] , [] , [4321] , Total Moves = 15  Enter the number of discs (-1 to exit): 5[54321] , [] , [] , Move Disc 1 From A To C[5432] , [] , [1] , Move Disc 2 From A To B[543] , [2] , [1] , Move Disc 1 From C To B[543] , [21] , [] , Move Disc 3 From A To C[54] , [21] , [3] , Move Disc 1 From B To A[541] , [2] , [3] , Move Disc 2 From B To C[541] , [] , [32] , Move Disc 1 From A To C[54] , [] , [321] , Move Disc 4 From A To B[5] , [4] , [321] , Move Disc 1 From C To B[5] , [41] , [32] , Move Disc 2 From C To A[52] , [41] , [3] , Move Disc 1 From B To A[521] , [4] , [3] , Move Disc 3 From C To B[521] , [43] , [] , Move Disc 1 From A To C[52] , [43] , [1] , Move Disc 2 From A To B[5] , [432] , [1] , Move Disc 1 From C To B[5] , [4321] , [] , Move Disc 5 From A To C[] , [4321] , [5] , Move Disc 1 From B To A[1] , [432] , [5] , Move Disc 2 From B To C

Page 140: C Programming With Solutions

[1] , [43] , [52] , Move Disc 1 From A To C[] , [43] , [521] , Move Disc 3 From B To A[3] , [4] , [521] , Move Disc 1 From C To B[3] , [41] , [52] , Move Disc 2 From C To A[32] , [41] , [5] , Move Disc 1 From B To A[321] , [4] , [5] , Move Disc 4 From B To C[321] , [] , [54] , Move Disc 1 From A To C[32] , [] , [541] , Move Disc 2 From A To B[3] , [2] , [541] , Move Disc 1 From C To B[3] , [21] , [54] , Move Disc 3 From A To C[] , [21] , [543] , Move Disc 1 From B To A[1] , [2] , [543] , Move Disc 2 From B To C[1] , [] , [5432] , Move Disc 1 From A To C[] , [] , [54321] , Total Moves = 31  Enter the number of discs (-1 to exit): 6[654321] , [] , [] , Move Disc 1 From A To B[65432] , [1] , [] , Move Disc 2 From A To C[6543] , [1] , [2] , Move Disc 1 From B To C[6543] , [] , [21] , Move Disc 3 From A To B[654] , [3] , [21] , Move Disc 1 From C To A[6541] , [3] , [2] , Move Disc 2 From C To B[6541] , [32] , [] , Move Disc 1 From A To B[654] , [321] , [] , Move Disc 4 From A To C[65] , [321] , [4] , Move Disc 1 From B To C[65] , [32] , [41] , Move Disc 2 From B To A[652] , [3] , [41] , Move Disc 1 From C To A[6521] , [3] , [4] , Move Disc 3 From B To C[6521] , [] , [43] , Move Disc 1 From A To B[652] , [1] , [43] , Move Disc 2 From A To C[65] , [1] , [432] , Move Disc 1 From B To C[65] , [] , [4321] , Move Disc 5 From A To B[6] , [5] , [4321] , Move Disc 1 From C To A[61] , [5] , [432] , Move Disc 2 From C To B[61] , [52] , [43] , Move Disc 1 From A To B[6] , [521] , [43] , Move Disc 3 From C To A[63] , [521] , [4] , Move Disc 1 From B To C[63] , [52] , [41] , Move Disc 2 From B To A[632] , [5] , [41] , Move Disc 1 From C To A[6321] , [5] , [4] , Move Disc 4 From C To B[6321] , [54] , [] , Move Disc 1 From A To B[632] , [541] , [] , Move Disc 2 From A To C[63] , [541] , [2] , Move Disc 1 From B To C[63] , [54] , [21] , Move Disc 3 From A To B[6] , [543] , [21] , Move Disc 1 From C To A[61] , [543] , [2] , Move Disc 2 From C To B[61] , [5432] , [] , Move Disc 1 From A To B[6] , [54321] , [] , Move Disc 6 From A To C[] , [54321] , [6] , Move Disc 1 From B To C[] , [5432] , [61] , Move Disc 2 From B To A[2] , [543] , [61] , Move Disc 1 From C To A[21] , [543] , [6] , Move Disc 3 From B To C[21] , [54] , [63] , Move Disc 1 From A To B[2] , [541] , [63] , Move Disc 2 From A To C[] , [541] , [632] , Move Disc 1 From B To C[] , [54] , [6321] , Move Disc 4 From B To A

Page 141: C Programming With Solutions

[4] , [5] , [6321] , Move Disc 1 From C To A[41] , [5] , [632] , Move Disc 2 From C To B[41] , [52] , [63] , Move Disc 1 From A To B[4] , [521] , [63] , Move Disc 3 From C To A[43] , [521] , [6] , Move Disc 1 From B To C[43] , [52] , [61] , Move Disc 2 From B To A[432] , [5] , [61] , Move Disc 1 From C To A[4321] , [5] , [6] , Move Disc 5 From B To C[4321] , [] , [65] , Move Disc 1 From A To B[432] , [1] , [65] , Move Disc 2 From A To C[43] , [1] , [652] , Move Disc 1 From B To C[43] , [] , [6521] , Move Disc 3 From A To B[4] , [3] , [6521] , Move Disc 1 From C To A[41] , [3] , [652] , Move Disc 2 From C To B[41] , [32] , [65] , Move Disc 1 From A To B[4] , [321] , [65] , Move Disc 4 From A To C[] , [321] , [654] , Move Disc 1 From B To C[] , [32] , [6541] , Move Disc 2 From B To A[2] , [3] , [6541] , Move Disc 1 From C To A[21] , [3] , [654] , Move Disc 3 From B To C[21] , [] , [6543] , Move Disc 1 From A To B[2] , [1] , [6543] , Move Disc 2 From A To C[] , [1] , [65432] , Move Disc 1 From B To C[] , [] , [654321] , Total Moves = 63   Enter the number of discs (-1 to exit): -1 

3. Sample Queue and Regular Sorting

Source Code

#include <alloc.h>#include <stdlib.h>#include <string.h>#include <stdio.h> typedef struct _MyQueue{    int *m_data;    int m_numElements;} MyQueue; int size(MyQueue *q){        return q->m_numElements;} int front(MyQueue *q){        if(q->m_numElements > 0)            return q->m_data[0];        return -1;} int push(MyQueue *q, int data){

Page 142: C Programming With Solutions

        if(q->m_data == NULL) // root node        {            q->m_numElements = 1;            q->m_data = (int*) malloc(sizeof(int));        }        else        {            q->m_numElements++;            q->m_data = (int*) realloc(q->m_data, q->m_numElements * sizeof(int));        }         q->m_data[q->m_numElements - 1] = data;        return 1; } int pop(MyQueue *q){        if(q->m_data == NULL) // root node        {            q->m_numElements = 0;            return 0;        }        else        {            if(q->m_numElements == 1)            {                // last item                q->m_numElements = 0;                free(q->m_data);                q->m_data = NULL;            }            else            {                q->m_numElements--;                memmove(q->m_data, &q->m_data[1], q->m_numElements * sizeof(int));                q->m_data = (int*) realloc(q->m_data, q->m_numElements * sizeof(int));            }        }        return 1;} int Sort(MyQueue *q){        int i, j, temp;        for(i = 1; i < q->m_numElements; i++)        {            for(j = 0; j < q->m_numElements - i; j++)            {                if(q->m_data[j] > q->m_data[j + 1])                {                    temp = q->m_data[j];                    q->m_data[j] = q->m_data[j + 1];                    q->m_data[j + 1] = temp;                }            }        }

Page 143: C Programming With Solutions

        return 1;} void Clear(MyQueue *q){        free(q->m_data);        q->m_data = NULL;        q->m_numElements = 0; }  int main(){    MyQueue *q1 = malloc(sizeof(MyQueue));    int i, sz1;    char inpstring[32];     printf("Enter Queue : ");    scanf("%s", inpstring);     for( i = 0; i < strlen(inpstring); i++)        push(q1,inpstring[i] - '0');      sz1 = size(q1);    Sort(q1);     printf("Displaying Queue : %d elements\n", sz1);    for(i = 0; i < sz1; i++)    {        int m = front(q1);        printf("%d", m);        pop(q1);    }    printf("\n");     Clear(q1);    free(q1);    return 0;}

 

Output

Enter Queue: 543126Displaying Queue: 5 elements123456Press any key to continue . . .

4. Sample Stack Implementation

Source Code

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

Page 144: C Programming With Solutions

#include <stdlib.h>#include <string.h> typedef struct _MyStack{    int *m_data;    int m_numElements;} MyStack; int push(MyStack *s, int data){        if(s->m_data == NULL) // root node        {            s->m_numElements = 1;            s->m_data = (int*) malloc(sizeof(int));        }        else        {            s->m_numElements++;            s->m_data = realloc(s->m_data, s->m_numElements * sizeof(int));            memmove(&s->m_data[1], s->m_data, (s->m_numElements - 1) * sizeof(int));        }         s->m_data[0] = data;        return 1;} int pop(MyStack *s){        if(s->m_data == NULL) // root node        {                s->m_numElements = 0;                return 0;        }        else        {            if(s->m_numElements == 1)            {                // last item                s->m_numElements = 0;                free(s->m_data);                s->m_data = NULL;            }            else            {                s->m_numElements--;                memmove(s->m_data, &s->m_data[1], s->m_numElements * sizeof(int));                s->m_data = (int*) realloc(s->m_data, s->m_numElements * sizeof(int));            }        }        return 1;} int top(MyStack *s){        if(s->m_numElements > 0)            return s->m_data[0];

Page 145: C Programming With Solutions

        return 0;} int size(MyStack *s){        return s->m_numElements;} int main(){    MyStack *s1 = malloc(sizeof(MyStack));    int sz, i;     push(s1, 10);    push(s1, 20);    push(s1, 30);    push(s1, 40);    pop(s1);    push(s1, 40);    push(s1, 50);     sz = size(s1);    for(i = 0; i < sz; i++)    {        printf("%d\n", top(s1));        pop(s1);    }     return 0;} 

Output

5040302010Press any key to continue . . .

5.InFix to PostFix ConversionSource Code#include <stdio.h>#include <stdlib.h>#include <string.h> typedef struct _MyStack{ char *m_data; int m_numElements;} MyStack;

Page 146: C Programming With Solutions

int push(MyStack *s, char chData){ if(s->m_data == NULL) // root node { s->m_numElements = 1; s->m_data = (char*) malloc(sizeof(char)); } else { s->m_numElements++; s->m_data = (char*)realloc(s->m_data, s->m_numElements * sizeof(char)); memmove(&s->m_data[1], s->m_data, (s->m_numElements - 1) * sizeof(char)); } s->m_data[0] = chData; return 1;} int pop(MyStack *s){ if(s->m_data == NULL) // root node { s->m_numElements = 0; return 0; } else { if(s->m_numElements == 1) { // last item s->m_numElements = 0; free(s->m_data); s->m_data = NULL; return 0; } else { s->m_numElements--; memmove(s->m_data, &s->m_data[1], s->m_numElements * sizeof(char)); s->m_data = (char*) realloc(s->m_data, s->m_numElements * sizeof(char)); } } return 1;}

Page 147: C Programming With Solutions

char top(MyStack *s){ if(s->m_numElements > 0) return s->m_data[0]; return 0;} int size(MyStack *s){ return s->m_numElements;} int main(int argc, char *argv[]){ MyStack *s1 = (MyStack *)malloc(sizeof(MyStack)); int sz, i, j, len, priority; char infix[512], postfix[512]; char *p = infix; int postfixlen = 0; memset(postfix, 0, sizeof(postfix)); memset((void*)s1, 0, sizeof(MyStack)); if(argc != 2) { printf("Usage: InFixCnv.exe <infix expression>\n"); exit(0); } strcpy(infix, argv[1]); while(1) { if(p == 0 || *p == '\0') { len = size(s1); if(len <= 0) break; else for(j = 0; j < len; j++) { postfix[postfixlen++] = top(s1); pop(s1); } } if(*p == '+' || *p == '-' || *p == '*' || *p == '/')

Page 148: C Programming With Solutions

{ // check the precedence if(size(s1) <= 0) push(s1, *p); else { if( top(s1) == '*' || top(s1) == '/') priority = 1; else priority = 0; if(priority == 1) { if(*p == '+' || *p == '-') { postfix[postfixlen++] = top(s1); pop(s1); p--; } else { postfix[postfixlen++] = top(s1); pop(s1); p--; } } else { if(*p == '+' || *p == '-') { postfix[postfixlen++] = top(s1); pop(s1); push(s1, *p); } else push(s1, *p); } } } else { postfix[postfixlen++] = *p; } p++; } printf("InFix :\t%s\n", infix);

Page 149: C Programming With Solutions

printf("PostFix:\t%s\n", postfix); return 0; }Click here to download Turbo C Source Code and ExecutableOutputInFix : a+b*cPostFix: abc*+

InFix : a+b*c/d-ePostFix: abc*d/+e- InFix : a+b*c/d-e+f*h/i+j-kPostFix: abc*d/+e-fh*i/+j+k- Press any key to continue . . .

6.  Employee Master File Creation with FILE*Source Code#include <iostream.h>#include <stdlib.h> class TEmployee{public: char name[64]; int age; char dept[48]; char addr1[64]; char addr2[64]; char city[48]; char state[48]; char zipcode[12];}; int ReadRecords(const char *fileName, TEmployee *e, int Sz){ int i = 0; int nTotalRecordsRead = 0; char buf[4096]; FILE *istream = fopen(fileName, "rb"); if (istream == 0)

Page 150: C Programming With Solutions

return false; for(i = 0; i < Sz; i++) { if(feof(istream)) break; int nBytesRead = fread(buf, 1, sizeof(TEmployee), istream); if(nBytesRead < sizeof(TEmployee)) break; char *p = reinterpret_cast<char*>(&e[i]); memcpy(p, buf, sizeof(TEmployee)); nTotalRecordsRead++; } fclose(istream); return nTotalRecordsRead;} int WriteRecords(const char *fileName, TEmployee *e, int Sz){ int i = 0; int nTotalRecordsWritten = 0; char buf[4096]; FILE *ostream = fopen(fileName, "wb"); if (ostream == 0) return false; for(i = 0; i < Sz; i++) { fwrite((char*)&e[i], 1, sizeof(TEmployee), ostream); nTotalRecordsWritten++; } fclose(ostream); return true;} TEmployee wremplList[100];TEmployee rdemplList[100];

void main(){

Page 151: C Programming With Solutions

int i, Sz; for(i = 0; i < 10; i++) { strcpy(wremplList[i].name, "victor"); strcpy(wremplList[i].dept, "CS"); wremplList[i].age = 23; } WriteRecords("c:\\kathir\\2.bin", wremplList, 10); Sz = ReadRecords("c:\\kathir\\2.bin", rdemplList, 100); for(i = 0; i < Sz; i++) { std::cout << rdemplList[i].name << "\t"; std::cout << rdemplList[i].age << "\t"; std::cout << rdemplList[i].dept << "\n"; } }Output victor CS 23victor CS 23victor CS 23victor CS 23victor CS 23victor CS 23victor CS 23victor CS 23victor CS 23

7. Displaying Yearly Calendar Given Year and First Day of Year

Source Code#include <stdio.h>#include <stdlib.h>#include <string.h>

int IsLeapYear(int year){ if((year % 4) == 0) { if((year % 100) == 0) { if( (year % 400) == 0) return 1; else

Page 152: C Programming With Solutions

return 0; } else return 1; } return 0;} int main(){ static int arrnumdays[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; static int arrleapnumdays[12] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; static char *strMonthName[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", }; int numdays; int *pdaysinmonth = 0; int year, firstdayofyear, firstdayofmonth, month, i, j; ::system("cls"); printf("Enter First Day of Year(1 - Sunday, 7 - Saturday): "); scanf("%d", &firstdayofyear); printf("Enter Year: "); scanf("%d", &year); if(firstdayofyear < 1 || firstdayofyear > 7) { printf("Invalid First Day Of Year. Enter 1 - Sunday, ..., 7 - Saturday.\n"); return 0; } pdaysinmonth = ( IsLeapYear(year)) ? arrleapnumdays : arrnumdays; ::system("cls"); printf("\n"); firstdayofmonth = 0; for(month = 0; month < 12; month++) { printf("\n\n\n\t%s %d\n\n", strMonthName[month], year); printf(" S M T W T F S\n");

Page 153: C Programming With Solutions

numdays = pdaysinmonth[month]; if( month == 0) firstdayofmonth = firstdayofyear; else { firstdayofmonth = (firstdayofmonth + pdaysinmonth[month-1]) % 7; if(firstdayofmonth == 0) firstdayofmonth = 7; // 7 for saturday } for(j = 0; j < firstdayofmonth - 1; j++) printf(" "); for(i = 0; i < numdays; i++) { char buf[32]; sprintf(buf, " %d ", i + 1); if(i < 9) strcat(buf, " "); printf(buf); if( (i + firstdayofmonth) % 7 == 0) printf("\n"); } } printf("\n\n"); return 0;}

Click here to get the Turbo C Source code and executable

OutputEnter First Day of Year(1 - Sunday, 7 - Saturday): 3Enter Year: 2008 Jan 2008 S M T W T F S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

Page 154: C Programming With Solutions

Feb 2008 S M T W T F S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 Mar 2008 S M T W T F S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 Apr 2008 S M T W T F S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 May 2008 S M T W T F S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 Jun 2008 S M T W T F S

Page 155: C Programming With Solutions

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 Jul 2008 S M T W T F S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 Aug 2008 S M T W T F S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 Sep 2008 S M T W T F S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 Oct 2008 S M T W T F S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

Page 156: C Programming With Solutions

Nov 2008 S M T W T F S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 Dec 2008 S M T W T F S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 Enter First Day of Year(1 - Sunday, 7 - Saturday): 6Enter Year: 2010 Jan 2010 S M T W T F S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 Feb 2010 S M T W T F S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28

Page 157: C Programming With Solutions

Mar 2010 S M T W T F S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 Apr 2010 S M T W T F S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 May 2010 S M T W T F S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 Jun 2010 S M T W T F S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 Jul 2010 S M T W T F S

Page 158: C Programming With Solutions

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 Aug 2010 S M T W T F S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 Sep 2010 S M T W T F S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 Oct 2010 S M T W T F S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 Nov 2010 S M T W T F S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27

Page 159: C Programming With Solutions

28 29 30 Dec 2010 S M T W T F S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

8. Displaying Monthly Calendar Given any Date from year 1900

Source Code#include <stdio.h>#include <stdlib.h>#include <string.h> static long arrnumdays[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };static long arrleapnumdays[12] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; typedef enum _boolean { false, true} bool; bool IsLeapYear(long year){ if((year % 4) == 0) { if((year % 100) == 0) { if( (year % 400) == 0) return true; else return false; } else return true; } return false;} bool CheckDate(long date, long month, long year)

Page 160: C Programming With Solutions

{ if(year < 0 || year > 10000) return false; if(month < 1 || month > 12) return false; if(date < 1 || date > 31) return false; if(IsLeapYear(year) == true) { if( date > arrleapnumdays[month-1]) return false; } else if( date > arrnumdays[month-1]) return false; return true;} long GetNumDays(long begdate, long begmonth, long begyear, long enddate, long endmonth, long endyear){ long diffyears = endyear - begyear; long numdays = 0; long days = -1; long m, diffmonth, d1, d2, y; bool bLeap = false; if(diffyears < 0) return -1; // The start date is greater than end date if( CheckDate(begdate, begmonth, begyear) == false) return -2; // Not a valid start date if(CheckDate(enddate, endmonth, endyear) == false) return -3; // Not a valid end date if(diffyears == 0) // same year { diffmonth = endmonth - begmonth; if(diffmonth < 0) return -1; // The start date is greater than end date if(diffmonth == 0) { numdays = enddate - begdate; if(numdays < 0) return -1; // The start date is greater than end date

Page 161: C Programming With Solutions

return numdays; } else { bLeap = IsLeapYear(begyear); // Beg date of end of Beg month if(bLeap == true) days = arrleapnumdays[begmonth - 1]; else days = arrnumdays[begmonth - 1]; numdays += days - begdate; if(diffmonth > 1) { for(m = begmonth + 1; m <= endmonth - 1; m++) { if(bLeap == true) numdays += arrleapnumdays[m - 1]; else numdays += arrnumdays[m - 1]; } } // Beg of End month to End date numdays += enddate; } } else { // Beg Date to end of beg year (Dec 31, YYYY) bLeap = IsLeapYear(begyear); if(bLeap == true) days = arrleapnumdays[begmonth - 1]; else days = arrnumdays[begmonth - 1]; numdays += days - begdate; for(d1 = begmonth + 1; d1 <= 12; d1++) { if(bLeap == true) numdays += arrleapnumdays[d1 - 1]; else numdays += arrnumdays[d1 - 1]; } if(diffyears > 1)

Page 162: C Programming With Solutions

{ for(y = begyear + 1; y <= endyear - 1; y++) { if(IsLeapYear(y) == true) numdays += 366; else numdays += 365; } } // Beg of End Year (Jan 01, YYYY) to End Date bLeap = IsLeapYear(endyear); for(d2 = 1; d2 <= endmonth - 1; d2++) { if(bLeap == true) numdays += arrleapnumdays[d2 - 1]; else numdays += arrnumdays[d2 - 1]; } numdays += enddate; } return numdays;} long main(){ static char *strDayOfWeek[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; static char *strMonthName[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", }; char bd[128], ed[128]; char buf[32]; long i, j; long begdate, begmonth, begyear; long enddate, endmonth, endyear; long numdays1, numdays2, numdays; long dayofweek1, dayofweek2; long *pdaysinmonth = 0; begdate = 1; begmonth = 1;

Page 163: C Programming With Solutions

begyear = 1900; // Sunday ::system("cls"); printf("Enter Date: "); scanf("%ld", &enddate); printf("Enter Month: "); scanf("%ld", &endmonth); printf("Enter Year: "); scanf("%ld", &endyear); sprintf(bd, "(DD/MM/YYYY) %02d/%02d/%04d", begdate, begmonth, begyear); sprintf(ed, "%02d/%02d/%04d", enddate, endmonth, endyear); numdays1 = GetNumDays(begdate, begmonth, begyear, 1, endmonth, endyear); dayofweek1 = (numdays1 + 1) % 7; if(numdays1 < 0) { if(numdays1 == -1) printf("The start date is greater than end date\n"); else if(numdays1 == -2) printf("Not a valid start date\n"); else if(numdays1 == -3) printf("Not a valid end date\n"); return 0; } numdays2 = GetNumDays(begdate, begmonth, begyear, enddate, endmonth, endyear); dayofweek2 = (numdays2 + 1) % 7; pdaysinmonth = ( IsLeapYear(endyear)) ? arrleapnumdays : arrnumdays; numdays = pdaysinmonth[endmonth - 1]; printf("\n\n"); printf("\t%s %ld\n\n",strMonthName[endmonth - 1], endyear); printf(" S M T W T F S\n"); for(j = 0; j < dayofweek1; j++) printf(" "); for(i = 0; i < numdays; i++) { if(i + 1 == enddate) sprintf(buf, " %ld*", i + 1); else

Page 164: C Programming With Solutions

sprintf(buf, " %ld ", i + 1); if(i < 9) strcat(buf, " "); printf(buf); if( (i + 1 + dayofweek1) % 7 == 0) printf("\n"); } printf("\n\n"); return 0;}

Click here to get the Turbo C Source code and executable OutputEnter Date: 15Enter Month: 12Enter Year: 2010 Dec 2010 S M T W T F S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15* 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

9. Convert Numbers to Text (Words)Source Code#include <stdio.h>#include <string.h> bool HelperConvertNumberToText(int num, char *buf, int len){ static char *strones[] = { "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen", }; static char *strtens[] = { "Ten", "Twenty", "Thirty", "Fourty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety", "Hundred" };

Page 165: C Programming With Solutions

char result[1024]; int single, tens, hundreds; if(num > 1000) return false; hundreds = num / 100; num = num - hundreds * 100; if( num < 20) { tens = 0; // special case single = num; } else { tens = num / 10; num = num - tens * 10; single = num; } memset(result, 0, 1024); if(hundreds > 0) { strcat(result, strones[hundreds-1]); strcat(result, " Hundred "); } if(tens > 0) { strcat(result, strtens[tens-1]); strcat(result, " "); } if(single > 0) { strcat(result, strones[single-1]); strcat(result, " "); } if(len > strlen(result)) strcpy(buf, result); return true;} bool ConvertNumberToText(int num, char *buf, int len)

Page 166: C Programming With Solutions

{ char tres[1024]; char result[1024]; int thousands; int temp; if(num < 0 || num > 100000) { printf( " %d \t Not Supported\n", num); return false; } if( num == 0) { printf(" %d \t Zero\n", num); return false; } memset(result, 0, 1024); if(num < 1000) { HelperConvertNumberToText(num, (char*) &tres, 1024); strcat(result, tres); } else { thousands = num / 1000; temp = num - thousands * 1000; HelperConvertNumberToText(thousands, (char*) &tres, 1024); strcat(result, tres); strcat(result, "Thousand "); HelperConvertNumberToText(temp, (char*) &tres, 1024); strcat(result, tres); } if(len > strlen(result)) strcpy(buf, result); return true;} int main(){ int len = 1024; char result[1024]; int i, num;

Page 167: C Programming With Solutions

static int arrNum[] = { -1, 0, 5, 10, 15, 19, 20, 21, 25, 33, 49, 50, 72, 99, 100, 101, 117, 199, 200, 214, 517, 589, 999, 1000, 1010, 1018, 1200, 9890, 10119, 13535, 57019, 99999, 100000, 100001 }; for(i = 0; i < sizeof(arrNum) / sizeof(int); i++) { num = arrNum[i]; if( ConvertNumberToText(num, result, len) == true) printf("%d \t %d\n", num, result); } return 0;}

Output-1 Not Supported0 Zero5 Five10 Ten15 Fifteen19 Nineteen20 Twenty21 Twenty One25 Twenty Five33 Thirty Three49 Fourty Nine50 Fifty72 Seventy Two99 Ninety Nine100 One Hundred101 One Hundred One117 One Hundred Seventeen199 One Hundred Ninety Nine200 Two Hundred214 Two Hundred Fourteen517 Five Hundred Seventeen589 Five Hundred Eighty Nine999 Nine Hundred Ninety Nine1000 One Thousand1010 One Thousand Ten1018 One Thousand Eighteen1200 One Thousand Two Hundred

Page 168: C Programming With Solutions

9890 Nine Thousand Eight Hundred Ninety10119 Ten Thousand One Hundred Nineteen13535 Thirteen Thousand Five Hundred Thirty Five57019 Fifty Seven Thousand Nineteen99999 Ninety Nine Thousand Nine Hundred Ninety Nine100000 One Hundred Thousand100001 Not Supported

10. Sorting Algorithm - Bubble SortSource Code

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

int BubbleSort(){ int max; int *numarray = 0;int i,j,k;int temp;

printf("\nProgram for Ascending order of Numeric Values using BUBBLE SORT"); printf("\n\nEnter the total number of elements: "); scanf("%d", &max); numarray = (int*) malloc(int * max); for(i = 0; i < max; i++) { printf("\nEnter [%d] element: ", i + 1 ); scanf("%d", &numarray[i]); } printf("Before Sorting : "); for(k = 0; k < max; k++) printf("%d ", numarray[k]); printf("\n"); for(i = 1; i < max; i++) { for(j = 0; j < max - i; j++) { if(numarray[j] > numarray[j + 1]) {

Page 169: C Programming With Solutions

temp = numarray[j]; numarray[j] = numarray[j + 1]; numarray[j + 1] = temp; } } printf("After iteration %d": ", i); for(k = 0; k < max; k++) printf("%d ", numarray[k]);

printf("/*** %d biggest number(s) is(are) pushed to the end of the array ***/\n", i + 1); } printf("\n\nThe numbers in ascending orders are given below:\n\n"); for(int i = 0; i < max; i++) { printf("Sorted [%d] element: ",i + 1); printf("%d\n", numarray[i]); } free(numarray); return 0;} int main(){ BubbleSort(); return 0;}

Output Program for Ascending order of Numeric Values using BUBBLE SORT Enter the total number of elements: 8 Enter [1] element: 80Enter [2] element: 60Enter [3] element: 40Enter [4] element: 20Enter [5] element: 10Enter [6] element: 30Enter [7] element: 50Enter [8] element: 70 Before Sorting : 80 60 40 20 10 30 50 70After iteration 1: 60 40 20 10 30 50 70 80

Page 170: C Programming With Solutions

After iteration 2: 40 20 10 30 50 60 70 80After iteration 3: 20 10 30 40 50 60 70 80After iteration 4: 10 20 30 40 50 60 70 80After iteration 5: 10 20 30 40 50 60 70 80After iteration 6: 10 20 30 40 50 60 70 80After iteration 7: 10 20 30 40 50 60 70 80 The numbers in ascending orders are given below: Sorted [1] element: 10Sorted [2] element: 20Sorted [3] element: 30Sorted [4] element: 40Sorted [5] element: 50Sorted [6] element: 60Sorted [7] element: 70Sorted [8] element: 80

11. Sorting Algorithm - Insertion SortSource Code#include <stdio.h>#include <conio.h> int InsertionSort(){ int max; int *numarray = 0;int i,j,k,temp;

printf("\nProgram for Ascending order of Numeric Values using INSERTION SORT"); printf("\n\nEnter the total number of elements: "); scanf("%d", &max); numarray = (int*) malloc(sizeof(int) * max); for(i = 0; i < max; i++) { printf("\nEnter [%d] element: ", i + 1); scanf("%d", &numarray[i]); } printf("Before Sorting : "); for(k = 0; k < max; k++) printf("%d ", numarray[k]) printf("\n");

Page 171: C Programming With Solutions

for(i = 1; i < max; i++) { j = i; while(j > 0) { if(numarray[j-1] > numarray[j]) { temp = numarray[j - 1]; numarray[j - 1] = numarray[j]; numarray[j] = temp; j--; } else break; } printf("After iteration %d ": ", i); for(k = 0; k < max; k++) printf("%d ", numarray[k] ); printf("/*** %d numbers from the begining of the array are input and they are sorted ***/\n", i + 1); } printf("\n\nThe numbers in ascending orders are given below:\n\n"); for(i = 0; i < max; i++) { printf("Sorted [%d] element: %d\n",i + 1, numarray[i]); } free(numarray); return 0;} int main(){ InsertionSort(); return 0;}OutputProgram for Ascending order of Numeric Values using INSERTION SORT Enter the total number of elements: 8 Enter [1] element: 80Enter [2] element: 60Enter [3] element: 40Enter [4] element: 20

Page 172: C Programming With Solutions

Enter [5] element: 10Enter [6] element: 30Enter [7] element: 50Enter [8] element: 70 Before Sorting : 80 60 40 20 10 30 50 70After iteration 1: 60 80 40 20 10 30 50 70After iteration 2: 40 60 80 20 10 30 50 70After iteration 3: 20 40 60 80 10 30 50 70After iteration 4: 10 20 40 60 80 30 50 70After iteration 5: 10 20 30 40 60 80 50 70After iteration 6: 10 20 30 40 50 60 80 70After iteration 7: 10 20 30 40 50 60 70 80 The numbers in ascending orders are given below: Sorted [1] element: 10Sorted [2] element: 20Sorted [3] element: 30Sorted [4] element: 40Sorted [5] element: 50Sorted [6] element: 60Sorted [7] element: 70Sorted [8] element: 80

12. Decimal to Binary Conversion

Source Code

#include <stdio.h>#include <conio.h>  long ConvertDecimal2Binary(long dec){    long bin = 0, pos = 1;    while(dec > 0)    {        bin = bin + (dec % 2) * pos;        dec = dec / 2;        pos *= 10;    }    return bin;} int main(){    for(long i = 0; i < 128; i++)    {

Page 173: C Programming With Solutions

        if(i > 16)            i += 7;        printf("\n%3ld = %08ld", i, ConvertDecimal2Binary(i));    }    printf("\n\n");    return 0;}

Output

   0 = 00000000   1 = 00000001   2 = 00000010   3 = 00000011   4 = 00000100   5 = 00000101   6 = 00000110   7 = 00000111   8 = 00001000   9 = 00001001 10 = 00001010 11 = 00001011 12 = 00001100 13 = 00001101 14 = 00001110 15 = 00001111 16 = 00010000 24 = 00011000 32 = 00100000 40 = 00101000 48 = 00110000 56 = 00111000 64 = 01000000 72 = 01001000 80 = 01010000 88 = 01011000 96 = 01100000104 = 01101000112 = 01110000120 = 01111000128 = 10000000

13. Binary to Decimal ConversionSource Code#include <stdio.h>#include <conio.h>#include <dos.h>

Page 174: C Programming With Solutions

long ConvertDecimal2Binary(long dec){ long bin = 0, pos = 1; while(dec > 0) { bin = bin + (dec % 2) * pos; dec = dec / 2; pos *= 10; } return bin;} long ConvertBinary2Decimal(long bin){ long dec = 0, pos = 0; long factor = 1; while(bin > 0) { if( (bin % 10) == 1) { dec += factor; } bin /= 10; pos++; factor = factor * 2; } return dec;} int main(){ for(long i = 0; i < 128; i++) { if(i > 16) i += 7; long bin = ConvertDecimal2Binary(i); long dec = ConvertBinary2Decimal(bin); printf("\n%3ld = %08ld = %3ld", i, bin, dec); } printf("\n\n"); return 0;}

Page 175: C Programming With Solutions

Output 0 = 00000000 = 0 1 = 00000001 = 1 2 = 00000010 = 2 3 = 00000011 = 3 4 = 00000100 = 4 5 = 00000101 = 5 6 = 00000110 = 6 7 = 00000111 = 7 8 = 00001000 = 8 9 = 00001001 = 9 10 = 00001010 = 10 11 = 00001011 = 11 12 = 00001100 = 12 13 = 00001101 = 13 14 = 00001110 = 14 15 = 00001111 = 15 16 = 00010000 = 16 24 = 00011000 = 24 32 = 00100000 = 32 40 = 00101000 = 40 48 = 00110000 = 48 56 = 00111000 = 56 64 = 01000000 = 64 72 = 01001000 = 72 80 = 01010000 = 80 88 = 01011000 = 88 96 = 01100000 = 96104 = 01101000 = 104112 = 01110000 = 112120 = 01111000 = 120128 = 10000000 = 128 Press any key to continue . . .

14. Factorial of a Number using Recursion4! means = 1 * 2 * 3 * 4 = 245! means = 1 * 2 * 3 * 4 * 5 = 120 or (5 * 4!)6! means = 1 * 2 * 3 * 4 * 5 * 6 = 720 or (6 * 5!)

Recursion meaning the function calls itself.

Source Code#include <stdio.h>#include <conio.h>

Page 176: C Programming With Solutions

int Fact(int n){ if( n <= 1) return 1; return n * Fact(n - 1);}

int main(){ int i = 0;

for(i = 0; i <= 10; i++) { printf("\n%2d! = %d", i, Fact(i)); } printf("\n\n"); return 0;}

Output 0! = 11! = 12! = 23! = 64! = 245! = 1206! = 7207! = 50408! = 403209! = 36288010! = 3628800

15. Factorial of a Number with out using Recursion

4! means = 1 * 2 * 3 * 4 = 245! means = 1 * 2 * 3 * 4 * 5 = 120 or (5 * 4!)6! means = 1 * 2 * 3 * 4 * 5 * 6 = 720 or (6 * 5!)

Recursion meaning the function calls itself. Here is the program and its output for finding a factorial of a number with out using recursive function calls.

Source Code#include <stdio.h>

Page 177: C Programming With Solutions

#include <conio.h> int Factorial(int n){ int result = 1;int i = 0;

if( n <= 1) return 1; for(i = 2; i <= n; i++) { result = result * i; } return result;} int main(){ int i = 0; for(i = 0; i <= 10; i++) { printf("\n%2d! = %d", i, Factorial(i)); } printf("\n\n"); return 0;}

Output0! = 11! = 12! = 23! = 64! = 245! = 1206! = 7207! = 50408! = 403209! = 36288010! = 3628800

16. Square Root of a Given NumberSource Code#include <stdio.h>#include <math.h>

Page 178: C Programming With Solutions

double SQRTByGuess(double num){ // Assume that the number is less than 1,000,000. so that the maximum of SQRT would be 1000. // Lets assume the result is 1000. If you want you can increase this limit

double min = 0, max = 1000; double answer = 0; double test = 0; if(num < 0) { printf("Negative numbers are not allowed"); return -1; } else if(num == 0) return 0; while(1) { test = (min + max) / 2; answer = test * test; if( num > answer) { // min needs be moved min = test; } else if(num < answer) { // max needs be moved max = test; } if(num == answer) break; if(num > (answer - 0.0001) && num < (answer + 0.0001)) break; } return test;} int _tmain(int argc, _TCHAR* argv[]){

int i = 0;double t = 0;

Page 179: C Programming With Solutions

for(i = 1; i <= 100; i += 3) { t = SQRTByGuess(i); printf("\nSQRT(%d) = %.4lf, %.4lf", i, t, sqrt((double)i)); } return 0;}

OutputSQRT(1) = 1.0000, 1.0000SQRT(4) = 2.0000, 2.0000SQRT(7) = 2.6458, 2.6458SQRT(10) = 3.1623, 3.1623SQRT(13) = 3.6055, 3.6056SQRT(16) = 4.0000, 4.0000SQRT(19) = 4.3589, 4.3589SQRT(22) = 4.6904, 4.6904SQRT(25) = 5.0000, 5.0000SQRT(28) = 5.2915, 5.2915SQRT(31) = 5.5678, 5.5678SQRT(34) = 5.8309, 5.8310SQRT(37) = 6.0828, 6.0828SQRT(40) = 6.3246, 6.3246SQRT(43) = 6.5574, 6.5574SQRT(46) = 6.7823, 6.7823SQRT(49) = 7.0000, 7.0000SQRT(52) = 7.2111, 7.2111SQRT(55) = 7.4162, 7.4162SQRT(58) = 7.6158, 7.6158SQRT(61) = 7.8102, 7.8102SQRT(64) = 8.0000, 8.0000SQRT(67) = 8.1854, 8.1854SQRT(70) = 8.3666, 8.3666SQRT(73) = 8.5440, 8.5440SQRT(76) = 8.7178, 8.7178SQRT(79) = 8.8882, 8.8882SQRT(82) = 9.0554, 9.0554SQRT(85) = 9.2195, 9.2195SQRT(88) = 9.3808, 9.3808SQRT(91) = 9.5394, 9.5394SQRT(94) = 9.6954, 9.6954SQRT(97) = 9.8489, 9.8489SQRT(100) = 10.0000, 10.0000

Page 180: C Programming With Solutions

17. Find Square Root With Algorithm

Source Code#include <stdio.h>#include <math.h> double MySqrt(double x){ long numeric = (long) x; long n = numeric; long fraction =(long) ((x - numeric) * 1000000); // 6 digits long f = fraction; int numdigits = 0, fnumdigits = 0, currdigits = 0; int tempresult = 0; int bOdd = 0, part = 0, tens = 1; int fractioncount = 0; double result = 0; int k, f1, f2, i, num, temp, quotient; for(numdigits = 0; n >= 10; numdigits++) n = (n / 10); numdigits++; for(fnumdigits = 0; f >= 10; fnumdigits++) f = (f / 10); fnumdigits++; if( (numdigits % 2) == 1) bOdd = 1; while(1) { tens = 1; currdigits = (bOdd == 1) ? (numdigits - 1) : (numdigits - 2); for(k = 0; k < currdigits; k++) tens *= 10; part = numeric / tens; // Get the Nearest Multiplication Factor num = part; quotient = tempresult * 2; i = 0, temp = 0; for(i = 1; ;i++) { if(quotient == 0)

Page 181: C Programming With Solutions

{ if(num - i * i < 0) { tempresult = (i - 1); break; } } else { temp = quotient * 10 + i; if(num - i * temp < 0) { tempresult = quotient / 2 * 10 + i - 1; break; } } } // Done with Nearest Multiplication Factor f1 = tempresult / 10; f2 = tempresult % 10; if(f1 == 0) numeric = numeric - (tempresult * tempresult * tens); else numeric = numeric - ((f1 * 2 * 10 + f2) * f2 * tens); if(numeric == 0 && fraction == 0) { if(currdigits > 0) { // Handle the Zero case tens = 1; currdigits = currdigits / 2; for(k = 0; k < currdigits; k++) tens *= 10; tempresult *= tens; } break; } if(bOdd == 1) { numdigits -= 1; bOdd = 0; } else

Page 182: C Programming With Solutions

numdigits -= 2; if( numdigits <= 0) { if(numeric > 0 || fraction > 0) { if(fractioncount >= 5) break; // Handle the fraction part for integer numbers fractioncount++; numeric *= 100; if(fraction > 0) { // Handle the fraction part for real numbers fnumdigits -= 2; tens = 1; for(k = 0; k < fnumdigits; k++) tens *= 10; numeric += fraction / tens; fraction = fraction % tens; } numdigits += 2; } else break; } } if(fractioncount == 0) result = tempresult; else { tens = 1; for(k = 0; k < fractioncount; k++) tens *= 10; result = (double) tempresult / tens; } return result;} int main(){ double d = 0; for(d = 1; d < 250000; d += 1234.56979) printf("sqrt(%.5lf) = %.5lf %.5lf\n", d, MySqrt(d), sqrt(d));

Page 183: C Programming With Solutions

d = 250000; printf("sqrt(%.5lf) = %.5lf %.5lf\n", d, MySqrt(d), sqrt(d)); return 0;} Output sqrt(1.00000) = 1.00000 1.00000sqrt(1235.56979) = 35.15067 35.15067sqrt(2470.13958) = 49.70049 49.70050sqrt(3704.70937) = 60.86632 60.86632sqrt(4939.27916) = 70.28000 70.28001sqrt(6173.84895) = 78.57384 78.57384sqrt(7408.41874) = 86.07217 86.07217sqrt(8642.98853) = 92.96767 92.96767sqrt(9877.55832) = 99.38590 99.38591sqrt(11112.12811) = 105.41407 105.41408sqrt(12346.69790) = 111.11569 111.11570sqrt(13581.26769) = 116.53869 116.53870sqrt(14815.83748) = 121.72032 121.72032sqrt(16050.40727) = 126.69020 126.69020sqrt(17284.97706) = 131.47234 131.47234sqrt(18519.54685) = 136.08654 136.08654sqrt(19754.11664) = 140.54933 140.54934sqrt(20988.68643) = 144.87472 144.87473sqrt(22223.25622) = 149.07466 149.07467sqrt(23457.82601) = 153.15947 153.15948sqrt(24692.39580) = 157.13814 157.13814sqrt(25926.96559) = 161.01852 161.01853sqrt(27161.53538) = 164.80757 164.80757sqrt(28396.10517) = 168.51143 168.51144sqrt(29630.67496) = 172.13562 172.13563sqrt(30865.24475) = 175.68507 175.68507sqrt(32099.81454) = 179.16421 179.16421sqrt(33334.38433) = 182.57706 182.57706sqrt(34568.95412) = 185.92728 185.92728sqrt(35803.52391) = 189.21819 189.21819sqrt(37038.09370) = 192.45502 192.45284sqrt(38272.66349) = 195.63400 195.63400sqrt(39507.23328) = 198.76426 198.76427sqrt(40741.80307) = 201.84598 201.84599sqrt(41976.37286) = 204.88136 204.88136sqrt(43210.94265) = 207.87241 207.87242sqrt(44445.51244) = 210.82104 210.82104

Page 184: C Programming With Solutions

sqrt(45680.08223) = 213.73072 213.72899sqrt(46914.65202) = 216.59790 216.59790sqrt(48149.22181) = 219.42930 219.42931sqrt(49383.79160) = 222.22464 222.22464sqrt(50618.36139) = 224.98524 224.98525sqrt(51852.93118) = 227.71238 227.71239sqrt(53087.50097) = 230.40725 230.40725sqrt(54322.07076) = 233.07232 233.07096sqrt(55556.64055) = 235.70456 235.70456sqrt(56791.21034) = 238.30906 238.30906sqrt(58025.78013) = 240.88540 240.88541sqrt(59260.34992) = 243.43448 243.43449sqrt(60494.91971) = 245.95715 245.95715sqrt(61729.48950) = 248.45420 248.45420sqrt(62964.05929) = 250.92746 250.92640sqrt(64198.62908) = 253.37448 253.37448sqrt(65433.19887) = 255.79913 255.79914sqrt(66667.76866) = 258.20102 258.20102sqrt(67902.33845) = 260.58077 260.58077sqrt(69136.90824) = 262.93898 262.93898sqrt(70371.47803) = 265.27622 265.27623sqrt(71606.04782) = 267.59386 267.59306sqrt(72840.61761) = 269.89001 269.89001sqrt(74075.18740) = 272.16757 272.16757sqrt(75309.75719) = 274.42623 274.42623sqrt(76544.32698) = 276.66645 276.66645sqrt(77778.89677) = 278.88868 278.88868sqrt(79013.46656) = 281.09334 281.09334sqrt(80248.03635) = 283.28142 283.28084sqrt(81482.60614) = 285.45158 285.45158sqrt(82717.17593) = 287.60593 287.60594sqrt(83951.74572) = 289.74427 289.74428sqrt(85186.31551) = 291.86694 291.86695sqrt(86420.88530) = 293.97429 293.97429sqrt(87655.45509) = 296.06663 296.06664sqrt(88890.02488) = 298.14467 298.14430sqrt(90124.59467) = 300.20758 300.20759sqrt(91359.16446) = 302.25678 302.25679sqrt(92593.73425) = 304.29218 304.29219sqrt(93828.30404) = 306.31406 306.31406sqrt(95062.87383) = 308.32267 308.32268sqrt(96297.44362) = 310.31829 310.31829sqrt(97532.01341) = 312.30135 312.30116sqrt(98766.58320) = 314.27151 314.27151sqrt(100001.15299) = 316.22958 316.22959sqrt(101235.72278) = 318.17561 318.17562

Page 185: C Programming With Solutions

sqrt(102470.29257) = 320.10981 320.10981sqrt(103704.86236) = 322.03239 322.03239sqrt(104939.43215) = 323.94356 323.94356sqrt(106174.00194) = 325.84381 325.84352sqrt(107408.57173) = 327.73246 327.73247sqrt(108643.14152) = 329.61059 329.61059sqrt(109877.71131) = 331.47807 331.47807sqrt(111112.28110) = 333.33508 333.33509sqrt(112346.85089) = 335.18181 335.18182sqrt(113581.42068) = 337.01842 337.01843sqrt(114815.99047) = 338.84508 338.84508sqrt(116050.56026) = 340.66194 340.66194sqrt(117285.13005) = 342.46916 342.46917sqrt(118519.69984) = 344.26690 344.26690sqrt(119754.26963) = 346.05529 346.05530sqrt(120988.83942) = 347.83450 347.83450sqrt(122223.40921) = 349.60464 349.60465sqrt(123457.97900) = 351.36587 351.36588sqrt(124692.54879) = 353.11832 353.11832sqrt(125927.11858) = 354.86211 354.86211sqrt(127161.68837) = 356.59737 356.59738sqrt(128396.25816) = 358.32423 358.32424sqrt(129630.82795) = 360.04281 360.04281sqrt(130865.39774) = 361.75322 361.75323sqrt(132099.96753) = 363.45559 363.45559sqrt(133334.53732) = 365.15002 365.15002sqrt(134569.10711) = 366.83662 366.83662sqrt(135803.67690) = 368.51550 368.51550sqrt(137038.24669) = 370.18677 370.18677sqrt(138272.81648) = 371.85052 371.85053sqrt(139507.38627) = 373.50687 373.50688sqrt(140741.95606) = 375.15590 375.15591sqrt(141976.52585) = 376.79772 376.79773sqrt(143211.09564) = 378.43355 378.43242sqrt(144445.66543) = 380.06008 380.06008sqrt(145680.23522) = 381.68080 381.68080sqrt(146914.80501) = 383.29467 383.29467sqrt(148149.37480) = 384.90177 384.90177sqrt(149383.94459) = 386.50219 386.50219sqrt(150618.51438) = 388.09601 388.09601sqrt(151853.08417) = 389.68428 389.68331sqrt(153087.65396) = 391.26417 391.26417sqrt(154322.22375) = 392.83867 392.83867sqrt(155556.79354) = 394.40688 394.40689sqrt(156791.36333) = 395.96889 395.96889sqrt(158025.93312) = 397.52475 397.52476

Page 186: C Programming With Solutions

sqrt(159260.50291) = 399.07455 399.07456sqrt(160495.07270) = 400.61917 400.61836sqrt(161729.64249) = 402.15624 402.15624sqrt(162964.21228) = 403.68826 403.68826sqrt(164198.78207) = 405.21448 405.21449sqrt(165433.35186) = 406.73498 406.73499sqrt(166667.92165) = 408.24982 408.24983sqrt(167902.49144) = 409.75906 409.75907sqrt(169137.06123) = 411.26343 411.26276sqrt(170371.63102) = 412.76098 412.76099sqrt(171606.20081) = 414.25378 414.25379sqrt(172840.77060) = 415.74123 415.74123sqrt(174075.34039) = 417.22336 417.22337sqrt(175309.91018) = 418.70026 418.70026sqrt(176544.47997) = 420.17196 420.17196sqrt(177779.04976) = 421.63906 421.63853sqrt(179013.61955) = 423.10001 423.10001sqrt(180248.18934) = 424.55646 424.55646sqrt(181482.75913) = 426.00793 426.00793sqrt(182717.32892) = 427.45447 427.45448sqrt(183951.89871) = 428.89613 428.89614sqrt(185186.46850) = 430.33297 430.33297sqrt(186421.03829) = 431.76542 431.76503sqrt(187655.60808) = 433.19234 433.19235sqrt(188890.17787) = 434.61497 434.61498sqrt(190124.74766) = 436.03296 436.03297sqrt(191359.31745) = 437.44635 437.44636sqrt(192593.88724) = 438.85520 438.85520sqrt(193828.45703) = 440.25953 440.25953sqrt(195063.02682) = 441.65967 441.65940sqrt(196297.59661) = 443.05484 443.05485sqrt(197532.16640) = 444.44590 444.44591sqrt(198766.73619) = 445.83263 445.83263sqrt(200001.30598) = 447.21505 447.21506sqrt(201235.87577) = 448.59321 448.59322sqrt(202470.44556) = 449.96716 449.96716sqrt(203705.01535) = 451.33707 451.33692sqrt(204939.58514) = 452.70253 452.70253sqrt(206174.15493) = 454.06404 454.06404sqrt(207408.72472) = 455.42148 455.42148sqrt(208643.29451) = 456.77488 456.77488sqrt(209877.86430) = 458.12428 458.12429sqrt(211112.43409) = 459.46973 459.46973sqrt(212347.00388) = 460.81166 460.81125sqrt(213581.57367) = 462.14886 462.14887sqrt(214816.14346) = 463.48262 463.48262

Page 187: C Programming With Solutions

sqrt(216050.71325) = 464.81255 464.81256sqrt(217285.28304) = 466.13869 466.13870sqrt(218519.85283) = 467.46107 467.46107sqrt(219754.42262) = 468.77971 468.77972sqrt(220988.99241) = 470.09466 470.09466sqrt(222223.56220) = 471.40594 471.40594sqrt(223458.13199) = 472.71358 472.71358sqrt(224692.70178) = 474.01761 474.01762sqrt(225927.27157) = 475.31807 475.31807sqrt(227161.84136) = 476.61498 476.61498sqrt(228396.41115) = 477.90837 477.90837sqrt(229630.98094) = 479.19826 479.19827sqrt(230865.55073) = 480.48470 480.48470sqrt(232100.12052) = 481.76770 481.76770sqrt(233334.69031) = 483.04729 483.04730sqrt(234569.26010) = 484.32350 484.32351sqrt(235803.82989) = 485.59636 485.59637sqrt(237038.39968) = 486.86589 486.86589sqrt(238272.96947) = 488.13212 488.13212sqrt(239507.53926) = 489.39507 489.39507sqrt(240742.10905) = 490.65477 490.65478sqrt(241976.67884) = 491.91125 491.91125sqrt(243211.24863) = 493.16452 493.16452sqrt(244445.81842) = 494.41462 494.41462sqrt(245680.38821) = 495.66156 495.66157sqrt(246914.95800) = 496.90538 496.90538sqrt(248149.52779) = 498.14609 498.14609sqrt(249384.09758) = 499.38459 499.38372sqrt(250000.00000) = 500.00000 500.00000

18. Function Keys with bioskeySource Code#include <stdio.h>#include <stdlib.h>#include <conio.h>#include <bios.h>#include <ctype.h> #define F1_Key 0x3b00#define F2_Key 0x3c00#define F3_Key 0x3d00#define F4_Key 0x3e00#define F5_Key 0x3f00#define F6_Key 0x4000#define F7_Key 0x4100

Page 188: C Programming With Solutions

#define F8_Key 0x4200#define F9_Key 0x4300#define F10_Key 0x4400 int handle_keyevents(){ int key = bioskey(0); if (isalnum(key & 0xFF)) { printf("'%c' key pressed\n", key); return 0; } switch(key) { case F1_Key: printf("F1 Key Pressed"); break; case F2_Key: printf("F2 Key Pressed"); break; case F3_Key: printf("F3 Key Pressed"); break; case F4_Key: printf("F4 Key Pressed"); break; case F5_Key: printf("F5 Key Pressed"); break; case F6_Key: printf("F6 Key Pressed"); break; case F7_Key: printf("F7 Key Pressed"); break; case F8_Key: printf("F8 Key Pressed"); break; case F9_Key: printf("F9 Key Pressed"); break; case F10_Key: printf("F10 Key Pressed"); return -1; default:

Page 189: C Programming With Solutions

printf("%#02x\n", key); break; } printf("\n"); return 0;} void main(){ int key; printf("Press F10 key to Quit\n"); while(1) { key = bioskey(1); if(key > 0) { if(handle_keyevents() < 0) break; } }}

Click here to get the Turbo C Source Code and EXEOutputPress F10 key to Quit'a' key pressed's' key pressed'd' key pressed'f' key pressed'g' key pressed'f' key pressed'L' key pressed'Q' key pressed'R' key pressed'E' key pressed'Y' key pressed'U' key pressed'R' key pressed'J' key pressed'3' key pressed'4' key pressed'6' key pressedF1 Key Pressed

Page 190: C Programming With Solutions

F2 Key PressedF5 Key PressedF6 Key PressedF6 Key PressedF7 Key PressedF8 Key PressedF8 Key PressedF10 Key Pressed

19. Checking Leap yearSource Code#include <stdio.h> typedef enum _boolean{ true = 1, false = 0} bool; bool IsLeapYear(int year){ if((year % 4) == 0) { if((year % 100) == 0) { if( (year % 400) == 0) return true; else return false; } else return true; } return false;} int main(){ int begyear, endyear; int i; printf("Enter Begining Year: "); scanf("%d", &begyear); printf("Enter Ending year: "); scanf("%d", &endyear);

Page 191: C Programming With Solutions

printf("List of Leap Years Between: %d and %d\n", begyear, endyear); for(i = begyear; i < endyear; i++) { if( IsLeapYear(i) == true) { printf("%d\t", i); } } return 0;}OutputEnter Beginning Year: 1000Enter Ending year: 2100List of Leap Years Between: 1000 and 2100 1004 1008 1012 1016 1020 1024 1028 1032 1036 1040 1044 1048 1052 1056 1060 1064 1068 1072 1076 1080 1084 1088 1092 1096 1104 1108 1112 1116 1120 1124 1128 1132 1136 1140 1144 1148 1152 1156 1160 1164 1168 1172 1176 1180 1184 1188 1192 1196 1200 1204 1208 1212 1216 1220 1224 1228 1232 1236 1240 1244 1248 1252 1256 1260 1264 1268 1272 1276 1280 1284 1288 1292 1296 1304 1308 1312 1316 1320 1324 1328 1332 1336 1340 1344 1348 1352 1356 1360 1364 1368 1372 1376 1380 1384 1388 13921396 1404 1408 1412 1416 1420 1424 1428 1432 1436 1440 1444 1448 1452 1456 1460 1464 1468 1472 1476 1480 1484 1488 1492 1496 1504 1508 1512 1516 1520 1524 1528 1532 1536 1540 1544 1548 1552 1556 1560 1564 1568 1572 1576 1580 1584 1588 15921596 1600 1604 1608 1612 1616 1620 1624 1628 1632 1636 1640 1644 1648 1652 1656 1660 1664 1668 1672 1676 1680 1684 1688 1692 1696 1704 1708 1712 1716 1720 1724 1728 1732 1736 1740

Page 192: C Programming With Solutions

1744 1748 1752 1756 1760 1764 1768 1772 1776 1780 1784 17881792 1796 1804 1808 1812 1816 1820 1824 1828 1832 1836 1840 1844 1848 1852 1856 1860 1864 1868 1872 1876 1880 1884 1888 1892 1896 1904 1908 1912 1916 1920 1924 1928 1932 1936 1940 1944 1948 1952 1956 1960 1964 1968 1972 1976 1980 1984 19881992 1996 2000 2004 2008 20122016 2020 2024 2028 2032 20362040 2044 2048 2052 2056 2060 2064 2068 2072 2076 2080 2084 2088 2092 2096 Press any key to continue . . .

19. Time Span Finding the number of days between two daysSource Code#include <stdio.h>#include <conio.h> static int arrnumdays[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };static int arrleapnumdays[12] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; typedef enum _boolean{ true = 1, false = 0} bool; bool IsLeapYear(int year){ if((year % 4) == 0) { if((year % 100) == 0) { if( (year % 400) == 0) return true; else return false; } else

Page 193: C Programming With Solutions

return true; } return false;} bool CheckDate(int date, int month, int year){ if(year < 0 || year > 10000) return false; if(month < 1 || month > 12) return false; if(date < 1 || date > 31) return false; if(IsLeapYear(year) == true) { if( date > arrleapnumdays[month-1]) return false; } else if( date > arrnumdays[month-1]) return false; return true;} int GetNumDays(int begdate, int begmonth, int begyear, int enddate, int endmonth, int endyear){ int diffyears = endyear - begyear; int numdays = 0; int days = -1; int m, y, d1, d2; bool bLeap = false; if(diffyears < 0) return -1; // The start date is greater than end date if( CheckDate(begdate, begmonth, begyear) == false) return -2; // Not a valid start date if(CheckDate(enddate, endmonth, endyear) == false) return -3; // Not a valid end date if(diffyears == 0) // same year { int diffmonth = endmonth - begmonth; if(diffmonth < 0)

Page 194: C Programming With Solutions

return -1; // The start date is greater than end date if(diffmonth == 0) { numdays = enddate - begdate; if(numdays < 0) return -1; // The start date is greater than end date return numdays; } else { bLeap = IsLeapYear(begyear); // Beg date of end of Beg month if(bLeap == true) days = arrleapnumdays[begmonth - 1]; else days = arrnumdays[begmonth - 1]; numdays += days - begdate; if(diffmonth > 1) { for(m = begmonth + 1; m <= endmonth - 1; m++) { if(bLeap == true) numdays += arrleapnumdays[m - 1]; else numdays += arrnumdays[m - 1]; } } // Beg of End month to End date numdays += enddate; } } else { // Beg Date to end of beg year (Dec 31, YYYY) bLeap = IsLeapYear(begyear); if(bLeap == true) days = arrleapnumdays[begmonth - 1]; else days = arrnumdays[begmonth - 1]; numdays += days - begdate; for(d1 = begmonth + 1; d1 <= 12; d1++) { if(bLeap == true)

Page 195: C Programming With Solutions

numdays += arrleapnumdays[d1 - 1]; else numdays += arrnumdays[d1 - 1]; } if(diffyears > 1) { for(y = begyear + 1; y <= endyear - 1; y++) { if(IsLeapYear(y) == true) numdays += 366; else numdays += 365; } } // Beg of End Year (Jan 01, YYYY) to End Date bLeap = IsLeapYear(endyear); for(d2 = 1; d2 <= endmonth - 1; d2++) { if(bLeap == true) numdays += arrleapnumdays[d2 - 1]; else numdays += arrnumdays[d2 - 1]; } numdays += enddate; } return numdays;} int main(){ int begdate, begmonth, begyear; int enddate, endmonth, endyear; char bd[128], ed[128]; int numdays; printf("Enter Begin Date: "); scanf("%d", &begdate); printf("Enter Begin Month: "); scanf("%d", &begmonth); printf("Enter Begin Year: "); scanf("%d", &begyear); printf("Enter End Date: "); scanf("%d", &enddate);

Page 196: C Programming With Solutions

printf("Enter End Month: "); scanf("%d", &endmonth); printf("Enter End Year: "); scanf("%d", &endyear); sprintf(bd, "(DD/MM/YYYY) %02d/%02d/%04d", begdate, begmonth, begyear); sprintf(ed, "%02d/%02d/%04d", enddate, endmonth, endyear); numdays = GetNumDays(begdate, begmonth, begyear, enddate, endmonth, endyear); if(numdays== -1) printf("The start date is greater than end date\n"); else if(numdays == -2) printf("Not a valid start date\n"); else if(numdays == -3) printf("Not a valid end date\n"); else printf("Number of days Between %s and %s is : %d\n", bd, ed, numdays); return 0;}

OutputEnter Begin Date: 6Enter Begin Month: 2Enter Begin Year: 1978Enter End Date: 1Enter End Month: 11Enter End Year: 2010 Number of days Between (DD/MM/YYYY) 06/02/1978 and 01/11/2010 is : 11956 Press any key to continue . . . Enter Begin Date: 31Enter Begin Month: 2Enter Begin Year: 2010Enter End Date: 10Enter End Month: 10Enter End Year: 2010 Not a valid start date Press any key to continue . . .

Page 197: C Programming With Solutions

Enter Begin Date: 10Enter Begin Month: 10Enter Begin Year: 2010Enter End Date: 10Enter End Month: 10Enter End Year: 2000 The start date is greater than end date Press any key to continue . . .

20. Simple Student Grading Logic

Source Code#include <stdio.h> int main(){ int i, arrMark[10]; char *grade = 0; for(i = 0; i < 10; i++) { printf("Enter %d Student Mark: ", i + 1); scanf("%d", &arrMark[i]); } printf("\n\nNo\tMark\tGrade\n"); for(i = 0; i < 10; i++) { if(arrMark[i] > 100) grade = "Error"; else if(arrMark[i] > 90) grade = "A+"; else if(arrMark[i] > 70) grade = "B+"; else if(arrMark[i] > 50) grade = "C+"; else if(arrMark[i] > 30) grade = "C"; else grade = "F"; printf("%d\t%d\t%s\n", i + 1, arrMark[i], grade); } return 0;}

Page 198: C Programming With Solutions

OutputEnter 1 Student Mark: 65Enter 2 Student Mark: 76Enter 3 Student Mark: 89Enter 4 Student Mark: 95Enter 5 Student Mark: 20Enter 6 Student Mark: 45Enter 7 Student Mark: 55Enter 8 Student Mark: 67Enter 9 Student Mark: 89Enter 10 Student Mark: 29 No Mark Grade1 65 C+2 76 B+3 89 B+4 95 A+5 20 F6 45 C7 55 C+8 67 C+9 89 B+10 29 FPress any key to continue . . .

21. randomize, rand and srand functions for generating random numbers22. Using kbhit, getch and putch functions

23. Using Circle and setcolor, setbkcolor functionsSource Code #include <graphics.h>#include <math.h>#include <conio.h>#include <dos.h>#include <stdlib.h> void main(){ int i, grd, grm; detectgraph(&grd,&grm); initgraph(&grd, &grm, "");

Page 199: C Programming With Solutions

while(!kbhit()) { randomize(); setbkcolor(BLUE); setfillstyle(SOLID_FILL, BLUE); bar(1,1,638,478); setcolor(WHITE); rectangle(0,0,639,479); for(i = 0; i < 300; i++) { setcolor(rand() % 10); circle(rand() % 640, rand() % 480, rand() % 25); delay(1); } } getch(); closegraph();}

Output

Source Code #include <graphics.h>#include <math.h>#include <conio.h>#include <dos.h>#include <stdlib.h> void main(){ int i, grd, grm; detectgraph(&grd,&grm); initgraph(&grd, &grm, ""); while(!kbhit()) {

Page 200: C Programming With Solutions

randomize(); setbkcolor(BLUE); setfillstyle(SOLID_FILL, BLUE); bar(1,1,638,478); setcolor(WHITE); rectangle(0,0,639,479); for(i = 0; i < 300; i++) { setcolor(rand() % 10); circle(rand() % 640, rand() % 480, rand() % 25); delay(1); } } getch(); closegraph();}

Output

NOTE: The above programs are tested and given output programs. It is an internal programs.

This are the Very very important programs in the interview point of view.

WEBSITES: www.allinterview.com for c &ds interview questions.