Está en la página 1de 198

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;
};

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()
{
int numElements = sizeof(numbers) / sizeof(numbers[0]);
for(int i = 0; i <numElements; i++)

printf("%d\n", numbers[i]);

Output
10.11
10.12
10.13
10.14

5. STRING ARRAY INTILIZATION:


Source Code
#include
#include
#include
#include
#include

<stdio.h>
<stdlib.h>
<conio.h>
<bios.h>
<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

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
#include
#include
#include
#include
#include

<stdio.h>
<stdlib.h>
<conio.h>
<bios.h>
<string.h>

void main()
{
const char *p1 = "victor";
char *p2 = "victor";
const char * const p3 = "victor";
char * const p4 = "victor";
p1 =
p2 =
//p3
//p4

0;
0;
= 0; // Compilation Error
= 0; // Compilation Error

// strcpy(p1, "victor");
strcpy(p2, "victor"); //
// strcpy(p3, "victor");
strcpy(p4, "victor"); //
//
//
//
//

p1
p2
p3
p4

// Compilation Error
Compilation Error
// Compilation Error
Compilation Error

content can not be changed, but ptr can be changed


both content and ptr can be changed
Neither content not ptr can be changed
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");
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");
}
void EnterFunction()
{
IsEntered = 1;
}
void ExitFunction()
{
IsEntered = 2;

}
int main()
{
DisplayStatus();
EnterFunction();
DisplayStatus();
ExitFunction();
DisplayStatus();
}

return 0;

Output
Not initialized
Function Enters
Function 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 function
Welcome to my static function

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;
}

return 0;

Output
10
20
30
40
50
60
70
80
90
100

10
20
30
40
50
60
70
80
90
100

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)
{
printf("%d\n", i);
}
}
return 0;
}

Output

List of Armstrong Numbers between (100 - 999):


153
370
371
407

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;
}
}

Output
Program for Fibonacci Series
Enter the maximum number for Fibonacci Series:
Printing Fibonacci Series from 0 - 1000
0
1
1
2
3

5
8
13
21
34
55
89
144
233
377
610
987

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
{
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 loop

1
2
3
4
5
Using do while loop
1
2
3
4
5
Using for loop
1
2
3
4
5
Press 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++)
{
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


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

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): 1
1 is a ODD number.
Enter a number(-1 for Exit): 2
2 is a EVEN number.
Enter a number(-1 for Exit): 3
3 is a ODD number.
Enter a number(-1 for Exit): 4
4 is a EVEN number.
Enter a number(-1 for Exit): 5
5 is a ODD number.
Enter a number(-1 for Exit): 6
6 is a EVEN number.
Enter a number(-1 for Exit): 7
7 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))
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;
}
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
victor
rotciv

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++)
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
******
*****
****
***
**
*
**
***
****
*****
******
1
12
123
1234
12345
123456
12345
1234
123
12
1
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,
strcat(result,
}
if(tens > 0)
{
strcat(result,
strcat(result,
}
if(single > 0)
{
strcat(result,
strcat(result,
}

strones[hundreds-1]);
" Hundred ");

strtens[tens-1]);
" ");

strones[single-1]);
" ");

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);
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
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

11.

Not Supported
Zero
Five
Ten
Fifteen
Nineteen
Twenty
Twenty One
Twenty Five
Thirty Three
Fourty Nine
Fifty
Seventy Two
Ninety Nine
One Hundred
One Hundred One
One Hundred Seventeen
One Hundred Ninety Nine
Two Hundred
Two Hundred Fourteen
Five Hundred Seventeen
Five Hundred Eighty Nine
Nine Hundred Ninety Nine
One Thousand
One Thousand Ten
One Thousand Eighteen
One Thousand Two Hundred
Nine Thousand Eight Hundred Ninety
Ten Thousand One Hundred Nineteen
Thirteen Thousand Five Hundred Thirty Five
Fifty Seven Thousand Nineteen
Ninety Nine Thousand Nine Hundred Ninety Nine
One Hundred Thousand
Not Supported

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): ");
scanf("%s", buffer);
number = StringToNumber(buffer);
printf("Converted Number: %d\n", number);
if(number == -1)
break;
}

return 0;

Output

Example String: 5647


Result Value
1st Iteration: 5

2nd Iteration: 5 * 10 + 6 = 56
3rd Iteration: 56 * 10 + 5 = 564
4th 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");
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
#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:
*
**
***
****
*****
******
*******
********
*********
Pattern 2 - Right Aligned:
*********
********
*******
******
*****
****
***
**
*
Press any key to continue . . .

14.

Guess Number in 5 attempts

Source Code

#include
#include
#include
#include
#include

<stdio.h>
<math.h>
<conio.h>
<process.h>
<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);
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.
ATTEMPT 1: Enter the your number: 50
Your guess is MODERATELY HIGH
ATTEMPT 2: Enter the your number: 28
Your guess is SOMEWHAT HIGH
ATTEMPT 3: Enter the your number: 24
Your guess is SOMEWHAT HIGH
ATTEMPT 4: Enter the your number: 22
Your guess is SOMEWHAT LOW
ATTEMPT 5: Enter the your number: 23
Congrats! You have guessed the number correctly
Press 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;
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);

b);

switch(opcode)
{
case 1:
result = a
printf("%d
break;
case 2:
result = a
printf("%d
break;
case 3:
result = a
printf("%d
break;
case 4:
result = a
printf("%d
}

+ b;
+ %d = %d", a, b, result);
- b;
- %d = %d", a, b, result);
* b;
* %d = %d", a, b, result);
/ b;
/ %d = %d\n%d %% %d = %d", a, b, result, a, b, a %

break;

Output
Program for Addition, Subtraction, Multiplication and Division
Enter Your Choice: 1 - Add, 2 - Sub, 3 - Mul, 4 - Div: 1
Enter First Number: 5
Enter Second Number: 3

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

Enter First Number: 5


Enter Second Number: 3

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

5 * 3 = 15
Program for Addition, Subtraction, Multiplication and Division
Enter Your Choice: 1 - Add, 2 - Sub, 3 - Mul, 4 - Div: 4
Enter First Number: 5
Enter Second Number: 3
5 / 3 = 1
5 % 3 = 2
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++;
}
}
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;
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;
}
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]);
}

Output
// contents of words_input.txt
computer
science
school
schooling
information
technology

Welcome to Guess a Word


Your secret word is: **********
Guess now (To stop the program, enter #) :
victor
***h******
School
**********
Tech
*ech******
techno
techno****
technology
Congrats! 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);
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 <=
{
printf("Sub
scanf("%d",
}
AddRecord(name,

5; i++)
%d Mark:", i);
&marks[i-1]);
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
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)


{
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;
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;
}
}
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;
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
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");

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

Output

Pascal Triangle Program


Enter the number of rows: 11
1
1

1
1

7
8

3
4

10

21

15

28

10
20

35
56

1
5

15
35

70

6
21

56

1
7

28

1
8

1
1

9
10

36
45

84
120

126
210

126
252

84
210

36
120

9
45

1
10

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);

}
}

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

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)
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:121
The number 121 is a palindrome
Enter a number:565
The number 565 is a palindrome
Enter a number:98
The number 98 is NOT a palindrome
Enter a number:978
The 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;
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>
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

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;
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: 87
Words: 13
Lines: 2
Press any key to continue . . .

11.Fahrenheit to Celsius Converter


Source 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);
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,


return 0;

Output
Enter a number to use in Fahrenheit and Celsius Converter: 100
100.0000 F = 37.7778 C
100.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 =
28.0000 C =

-2.2222 C
82.4000 F

Press any key to continue . . .

13. Displaying ASCII Characters On Screen


Source Code
// Printing ASCII characters
#include
#include
#include
#include

<conio.h>
<process.h>
<dos.h>
<stdio.h>

int main()

248);

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 =
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 = <
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
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 =
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 =
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 =
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 . . .

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
105
115
125
135
145
150
151
152
153
154
155
156
157
158
159
165
175
185
195

Sum = 15150
Press 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>
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.: ");
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 range
Enter Beg. No.: 1
Enter End. No.: 100
The 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)
{
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 range
Enter Beg. No.: 1
Enter End. No.: 100
The 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);
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);
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;
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
#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
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);
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) &&
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 . . .

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);
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
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
px, 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 = 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 l
2y2,
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;
else
{
*intersection_X = (*c2 - *c1) / (*m1 - *m2);
*intersection_Y = *m1 * *intersection_X + *c1;
}
}
int LineSegmentIntersection(float l1x1, float l1y1, float l1x2, float l
1y2,
float l2x1, float l2y1, float l2x2, float l
2y2,
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;
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;
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)
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");
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

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
px, 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 )
{
return 1;
}
else
return 0;
}

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


1y2,
float l2x1, float l2y1, float l2x2, float l
2y2,
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;
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, flo
at 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;
}
int Calculate_Triangle_Type(float ax, float ay, float bx, float by, flo
at 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;
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;

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");
}

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 . . .

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, flo


at 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;

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

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
px, 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 )
{
return 1;
}
else
return 0;
}

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


1y2,
float l2x1, float l2y1, float l2x2, float l
2y2,
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;
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, flo
at 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 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);
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 . . .

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;

Output
25 is a perfect square of 5
36 is a perfect square of 6
49 is a perfect square of 7
64 is a perfect square of 8
68 is NOT a perfect square

127 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)
{
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

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
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;
}
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;
long result[MAX_SIZE];
long count =
int i = 0;

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 *

Press any key to continue . . .


Enter a Number: 48125
Prime Factors For 48125 = 11 *

7 *

5 *

5 *

5 *

Press any key to continue . . .

Prime Factor For 9360 = 13 *

19.

5 *

3 *

3 *

Calculate Mean

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

float CalculateMean(float *value, int max)

2 *

2 *

2 *

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: 10
Enter [1] Number: 6
Enter [2] Number: 7
Enter [3] Number: 8
Enter [4] Number: 7
Enter [5] Number: 6
Enter [6] Number: 5
Enter [7] Number: 2
Enter [8] Number: 2
Enter [9] Number: 9
Enter [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;
}

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: 10
Enter [1] Number: 6
Enter [2] Number: 7
Enter [3] Number: 8
Enter [4] Number: 7
Enter [5] Number: 6
Enter [6] Number: 5
Enter [7] Number: 2
Enter [8] Number: 2
Enter [9] Number: 9
Enter [10] Number: 3
Total Numbers: 10
Median: 6.000000

21. Calculate Range


Source Code
#include <stdlib.h>
#include <stdio.h>
#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: 10
Enter [1] Number: 6
Enter [2] Number: 7
Enter [3] Number: 8
Enter [4] Number: 7
Enter [5] Number: 6
Enter [6] Number: 5
Enter [7] Number: 2
Enter [8] Number: 2
Enter [9] Number: 9
Enter [10] Number: 3
Total Numbers: 10
Range: 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;
}
}
}
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;
}
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: 10
Enter [1] Number: 6
Enter [2] Number: 7
Enter [3] Number: 8
Enter [4] Number: 7
Enter [5] Number: 6
Enter [6] Number: 5
Enter [7] Number: 2
Enter [8] Number: 2
Enter [9] Number: 9
Enter [10] Number: 3
Total Numbers: 10
Mode: 2 6 7

22. Calculate Variance


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;
}
}
}
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;

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: 10
Enter [1] Number: 6
Enter [2] Number: 7
Enter [3] Number: 8
Enter [4] Number: 7
Enter [5] Number: 6
Enter [6] Number: 5

Enter
Enter
Enter
Enter

[7] Number: 2
[8] Number: 2
[9] Number: 9
[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] = "";
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++)
{
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
{
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++)
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);
}

return 0;

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

Total Numbers: 10
Mean: 5.500000
Median: 6.000000
Mode: 2 6 7
Range: 2 - 9
Sample Variance: 6.055555
Population Variance: 5.450000
Sample Stdandrd Deviation: 2.460804
Population 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)


{
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: 10
Enter Second Number: 135
GCD(10,135) = 5
LCM(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;
double termfactor = 0;
for(term = 1; term <
{
termfactor = 0;
termfactor = sqx
if(term % 2)
{
sineresult =
}
else
{
sineresult =
}
index++;
fact *= index;
index++;
fact *= index;
sqx *= (x*x);
}
}

return sineresult;

20; term++)
/ fact;
sineresult - termfactor;

sineresult + termfactor;

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
4.7500 = 0.0828
9.5000 = 0.1650
14.2500 = 0.2462
19.0000 = 0.3256
23.7500 = 0.4027
28.5000 = 0.4772
33.2500 = 0.5483
38.0000 = 0.6157
42.7500 = 0.6788
47.5000 = 0.7373
52.2500 = 0.7907
57.0000 = 0.8387
61.7500 = 0.8809
66.5000 = 0.9171
71.2500 = 0.9469
76.0000 = 0.9703
80.7500 = 0.9870
85.5000 = 0.9969
90.2500 = 1.0000
95.0000 = 0.9962
99.7500 = 0.9856
104.5000 = 0.9681
109.2500 = 0.9441
114.0000 = 0.9135
118.7500 = 0.8767
123.5000 = 0.8339
128.2500 = 0.7853
133.0000 = 0.7314
137.7500 = 0.6724
142.5000 = 0.6088
147.2500 = 0.5410
152.0000 = 0.4695
156.7500 = 0.3947
161.5000 = 0.3173
166.2500 = 0.2377
171.0000 = 0.1564
175.7500 = 0.0741
180.5000 = -0.0087
185.2500 = -0.0915
190.0000 = -0.1736
194.7500 = -0.2546
199.5000 = -0.3338
204.2500 = -0.4107

0.0000
0.0828
0.1650
0.2462
0.3256
0.4027
0.4772
0.5483
0.6157
0.6788
0.7373
0.7907
0.8387
0.8809
0.9171
0.9469
0.9703
0.9870
0.9969
1.0000
0.9962
0.9856
0.9681
0.9441
0.9135
0.8767
0.8339
0.7853
0.7314
0.6724
0.6088
0.5410
0.4695
0.3947
0.3173
0.2377
0.1564
0.0741
-0.0087
-0.0915
-0.1736
-0.2546
-0.3338
-0.4107

209.0000 = -0.4848
-0.4848
213.7500 = -0.5556
-0.5556
218.5000 = -0.6225
-0.6225
223.2500 = -0.6852
-0.6852
228.0000 = -0.7431
-0.7431
232.7500 = -0.7960
-0.7960
237.5000 = -0.8434
-0.8434
242.2500 = -0.8850
-0.8850
247.0000 = -0.9205
-0.9205
251.7500 = -0.9497
-0.9497
256.5000 = -0.9724
-0.9724
261.2500 = -0.9884
-0.9884
266.0000 = -0.9976
-0.9976
270.7500 = -0.9999
-0.9999
275.5000 = -0.9954
-0.9954
280.2500 = -0.9840
-0.9840
285.0000 = -0.9659
-0.9659
289.7500 = -0.9412
-0.9412
294.5000 = -0.9100
-0.9100
299.2500 = -0.8725
-0.8725
304.0000 = -0.8290
-0.8290
308.7500 = -0.7799
-0.7799
313.5000 = -0.7254
-0.7254
318.2500 = -0.6659
-0.6659
323.0000 = -0.6018
-0.6018
327.7500 = -0.5336
-0.5336
332.5000 = -0.4617
-0.4617
337.2500 = -0.3867
-0.3867
342.0000 = -0.3090
-0.3090
346.7500 = -0.2292
-0.2292
351.5000 = -0.1478
-0.1478
356.2500 = -0.0654
-0.0654
Press any key to continue . . .

26. Using Cosine Series to find COS Value


Cosine 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;
}

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

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

Press any key to continue . . .

27. Using Sine and Cosine Series to find TAN Value


sine 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 series
double 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 <
{
termfactor = 0;
termfactor = sqx
if(term % 2)
{
sineresult =
}
else
{
sineresult =
}
index++;
fact *= index;
index++;
fact *= index;
sqx *= (x*x);
}

/ fact;
sineresult - termfactor;

sineresult + termfactor;

sqx = x * x;
fact = 2;
index = 2;
for(term = 1; term <
{
termfactor = 0;
termfactor = sqx
if(term %2)
{
cosineresult
}
else
{
cosineresult
}
index++;
fact *= index;
index++;
fact *= index;
sqx *= (x*x);
}

20; term++)

20; term++)
/ fact;
= cosineresult - termfactor;

= cosineresult + termfactor;

}
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.0000
4.7500 = 0.0831 0.0831
9.5000 = 0.1673 0.1673
14.2500 = 0.2540
19.0000 = 0.3443
23.7500 = 0.4400
28.5000 = 0.5430
33.2500 = 0.6556
38.0000 = 0.7813
42.7500 = 0.9244
47.5000 = 1.0913
52.2500 = 1.2915
57.0000 = 1.5399
61.7500 = 1.8611
66.5000 = 2.2998
71.2500 = 2.9459
76.0000 = 4.0108
80.7500 = 6.1402
85.5000 = 12.7062
90.2500 = -229.1818
95.0000 = -11.4301
99.7500 = -5.8197
104.5000 = -3.8667
109.2500 = -2.8636
114.0000 = -2.2460
118.7500 = -1.8228
123.5000 = -1.5108
128.2500 = -1.2685
133.0000 = -1.0724
137.7500 = -0.9083
142.5000 = -0.7673
147.2500 = -0.6432
152.0000 = -0.5317
156.7500 = -0.4296
161.5000 = -0.3346
166.2500 = -0.2447
171.0000 = -0.1584
175.7500 = -0.0743
180.5000 = 0.0087
185.2500 = 0.0919

0.2540
0.3443
0.4400
0.5430
0.6556
0.7813
0.9244
1.0913
1.2915
1.5399
1.8611
2.2998
2.9459
4.0108
6.1402
12.7062
-229.1818
-11.4301
-5.8197
-3.8667
-2.8636
-2.2460
-1.8228
-1.5108
-1.2685
-1.0724
-0.9083
-0.7673
-0.6432
-0.5317
-0.4296
-0.3346
-0.2447
-0.1584
-0.0743
0.0087
0.0919

190.0000 = 0.1763
0.1763
194.7500 = 0.2633
0.2633
199.5000 = 0.3541
0.3541
204.2500 = 0.4505
0.4505
209.0000 = 0.5543
0.5543
213.7500 = 0.6682
0.6682
218.5000 = 0.7954
0.7954
223.2500 = 0.9407
0.9407
228.0000 = 1.1106
1.1106
232.7500 = 1.3151
1.3151
237.5000 = 1.5697
1.5697
242.2500 = 1.9007
1.9007
247.0000 = 2.3559
2.3559
251.7500 = 3.0326
3.0326
256.5000 = 4.1653
4.1653
261.2500 = 6.4971
6.4971
266.0000 = 14.3007
14.3007
270.7500 = -76.3900
-76.3900
275.5000 = -10.3854
-10.3854
280.2500 = -5.5301
-5.5301
285.0000 = -3.7321
-3.7321
289.7500 = -2.7852
-2.7852
294.5000 = -2.1943
-2.1943
299.2500 = -1.7856
-1.7856
304.0000 = -1.4826
-1.4826
308.7500 = -1.2460
-1.2460
313.5000 = -1.0538
-1.0538
318.2500 = -0.8925
-0.8925
323.0000 = -0.7536
-0.7536
327.7500 = -0.6310
-0.6310
332.5000 = -0.5206
-0.5206
337.2500 = -0.4193
-0.4193
342.0000 = -0.3249
-0.3249
346.7500 = -0.2355
-0.2355
351.5000 = -0.1495
-0.1495
356.2500 = -0.0655
-0.0655
Press any key to continue . . .

28. Quadratic Equation Solver - ax2 + bx + c = 0


x = [ -b +/- sqrt(b^2 - 4ac) ] / 2a
We have to find the value of (b*b - 4*a*c).
1.
2.
3.

When it is greater than Zero, we will get two Real Solutions.


When it is equal to zero, we will get one Real Solution.
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) ] / 2a
void 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
{
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 = 0
SolveQuadratic(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 Value
exp(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>
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
-1.9000
-1.8000
-1.7000
-1.6000
-1.5000
-1.4000
-1.3000
-1.2000
-1.1000
-1.0000
-0.9000
-0.8000
-0.7000
-0.6000
-0.5000
-0.4000
-0.3000
-0.2000
-0.1000
0.0000
0.1000
0.2000
0.3000
0.4000
0.5000
0.6000
0.7000
0.8000
0.9000
1.0000
1.1000
1.2000
1.3000
1.4000
1.5000
1.6000
1.7000
1.8000
1.9000
2.0000
2.1000
2.2000
2.3000
2.4000
2.5000
2.6000
2.7000
2.8000

=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=

0.1353
0.1496
0.1653
0.1827
0.2019
0.2231
0.2466
0.2725
0.3012
0.3329
0.3679
0.4066
0.4493
0.4966
0.5488
0.6065
0.6703
0.7408
0.8187
0.9048
1.0000
1.1052
1.2214
1.3499
1.4918
1.6487
1.8221
2.0138
2.2255
2.4596
2.7183
3.0042
3.3201
3.6693
4.0552
4.4817
4.9530
5.4739
6.0496
6.6859
7.3891
8.1662
9.0250
9.9742
11.0232
12.1825
13.4637
14.8797
16.4446

0.1353 0.1353
0.1496 0.1496
0.1653 0.1653
0.1827 0.1827
0.2019 0.2019
0.2231 0.2231
0.2466 0.2466
0.2725 0.2725
0.3012 0.3012
0.3329 0.3329
0.3679 0.3679
0.4066 0.4066
0.4493 0.4493
0.4966 0.4966
0.5488 0.5488
0.6065 0.6065
0.6703 0.6703
0.7408 0.7408
0.8187 0.8187
0.9048 0.9048
1.0000 1.0000
1.1052 1.1052
1.2214 1.2214
1.3499 1.3499
1.4918 1.4918
1.6487 1.6487
1.8221 1.8221
2.0138 2.0138
2.2255 2.2255
2.4596 2.4596
2.7183 2.7183
3.0042 3.0042
3.3201 3.3201
3.6693 3.6693
4.0552 4.0552
4.4817 4.4817
4.9530 4.9530
5.4739 5.4739
6.0496 6.0496
6.6859 6.6859
7.3891 7.3890
8.1662 8.1662
9.0250 9.0250
9.9742 9.9742
11.0232 11.0232
12.1825 12.1825
13.4637 13.4637
14.8797 14.8797
16.4446 16.4446

2.9000 = 18.1741 18.1741 18.1741


Press 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: ");
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 . . .

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;
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:");
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: 123
123
132
213
231
312
321
Count: 6
Press any key to continue . . .
Enter a string to find permutation: 4123

4123
4132
4213
4231
4312
4321
Count: 6
Press 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: 4123
1234
1243
1324
1342
1423
1432
2134
2143
2314
2341
2413
2431
3124
3142
3214
3241
3412
3421
4123
4132
4213
4231
4312
4321
Count: 24
Press any key to continue . . .

2. Tower Of Hanoi Algorithm Source Code


Source Code
#include
#include
#include
#include

<stdio.h>
<alloc.h>
<stdlib.h>
<string.h>

typedef struct _MyStack


{
int *m_data;

int m_numElements;
} MyStack;
static
static
static
static

int
int
int
int

movecount = 0;
countA = 0;
countB = 0;
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));
}
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)
{
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
else
printf("Move Disc %d From C To
}
else if (diffB == 1)
{
if (diffA == -1)
printf("Move Disc %d From A To
else
printf("Move Disc %d From C To
}
else //if (diffC == 1)
{
if (diffA == -1)
printf("Move Disc %d From A To

A", top(A));
A", top(A));

B", top(B));
B", top(B));

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++;
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();
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): 0
Enter between 2 - 9
Enter the number of discs (-1 to exit): 1
Enter between 2 - 9
Enter the number
[21] , [] , [] ,
[2] , [1] , [] ,
[] , [1] , [2] ,
[] , [] , [21] ,

of discs (-1 to exit): 2


Move Disc 1 From A To B
Move Disc 2 From A To C
Move Disc 1 From B To C
Total Moves = 3

Enter the number of discs (-1


[321] , [] , [] , Move Disc 1
[32] , [] , [1] , Move Disc 2
[3] , [2] , [1] , Move Disc 1
[3] , [21] , [] , Move Disc 3
[] , [21] , [3] , Move Disc 1
[1] , [2] , [3] , Move Disc 2
[1] , [] , [32] , Move Disc 1
[] , [] , [321] , Total Moves
Enter the number
[4321] , [] , []
[432] , [1] , []
[43] , [1] , [2]
[43] , [] , [21]
[4] , [3] , [21]
[41] , [3] , [2]
[41] , [32] , []
[4] , [321] , []
[] , [321] , [4]
[] , [32] , [41]
[2] , [3] , [41]
[21] , [3] , [4]
[21] , [] , [43]
[2] , [1] , [43]
[] , [1] , [432]
[] , [] , [4321]

to exit):
From A To
From A To
From C To
From A To
From B To
From B To
From A To
= 7

3
C
B
B
C
A
C
C

of discs (-1 to exit): 4


, Move Disc 1 From A To B
, Move Disc 2 From A To C
, Move Disc 1 From B To C
, Move Disc 3 From A To B
, Move Disc 1 From C To A
, Move Disc 2 From C To B
, Move Disc 1 From A To B
, Move Disc 4 From A To C
, Move Disc 1 From B To C
, Move Disc 2 From B To A
, Move Disc 1 From C To A
, Move Disc 3 From B To C
, Move Disc 1 From A To B
, Move Disc 2 From A To C
, Move Disc 1 From B To C
, Total Moves = 15

Enter the number of


[54321] , [] , [] ,
[5432] , [] , [1] ,
[543] , [2] , [1] ,
[543] , [21] , [] ,
[54] , [21] , [3] ,
[541] , [2] , [3] ,
[541] , [] , [32] ,
[54] , [] , [321] ,
[5] , [4] , [321] ,
[5] , [41] , [32] ,
[52] , [41] , [3] ,
[521] , [4] , [3] ,
[521] , [43] , [] ,
[52] , [43] , [1] ,
[5] , [432] , [1] ,
[5] , [4321] , [] ,
[] , [4321] , [5] ,
[1] , [432] , [5] ,
[1] , [43] , [52] ,
[] , [43] , [521] ,
[3] , [4] , [521] ,
[3] , [41] , [52] ,
[32] , [41] , [5] ,
[321] , [4] , [5] ,
[321] , [] , [54] ,
[32] , [] , [541] ,
[3] , [2] , [541] ,
[3] , [21] , [54] ,
[] , [21] , [543] ,
[1] , [2] , [543] ,
[1] , [] , [5432] ,
[] , [] , [54321] ,

discs (-1 to exit): 5


Move Disc 1 From A To
Move Disc 2 From A To
Move Disc 1 From C To
Move Disc 3 From A To
Move Disc 1 From B To
Move Disc 2 From B To
Move Disc 1 From A To
Move Disc 4 From A To
Move Disc 1 From C To
Move Disc 2 From C To
Move Disc 1 From B To
Move Disc 3 From C To
Move Disc 1 From A To
Move Disc 2 From A To
Move Disc 1 From C To
Move Disc 5 From A To
Move Disc 1 From B To
Move Disc 2 From B To
Move Disc 1 From A To
Move Disc 3 From B To
Move Disc 1 From C To
Move Disc 2 From C To
Move Disc 1 From B To
Move Disc 4 From B To
Move Disc 1 From A To
Move Disc 2 From A To
Move Disc 1 From C To
Move Disc 3 From A To
Move Disc 1 From B To
Move Disc 2 From B To
Move Disc 1 From A To
Total Moves = 31

Enter the number of discs


[654321] , [] , [] , Move
[65432] , [1] , [] , Move
[6543] , [1] , [2] , Move
[6543] , [] , [21] , Move
[654] , [3] , [21] , Move
[6541] , [3] , [2] , Move
[6541] , [32] , [] , Move
[654] , [321] , [] , Move
[65] , [321] , [4] , Move
[65] , [32] , [41] , Move
[652] , [3] , [41] , Move
[6521] , [3] , [4] , Move
[6521] , [] , [43] , Move
[652] , [1] , [43] , Move
[65] , [1] , [432] , Move
[65] , [] , [4321] , Move
[6] , [5] , [4321] , Move
[61] , [5] , [432] , Move
[61] , [52] , [43] , Move
[6] , [521] , [43] , Move

(-1 to
Disc 1
Disc 2
Disc 1
Disc 3
Disc 1
Disc 2
Disc 1
Disc 4
Disc 1
Disc 2
Disc 1
Disc 3
Disc 1
Disc 2
Disc 1
Disc 5
Disc 1
Disc 2
Disc 1
Disc 3

exit):
From A
From A
From B
From A
From C
From C
From A
From A
From B
From B
From C
From B
From A
From A
From B
From A
From C
From C
From A
From C

6
To
To
To
To
To
To
To
To
To
To
To
To
To
To
To
To
To
To
To
To

C
B
B
C
A
C
C
B
B
A
A
B
C
B
B
C
A
C
C
A
B
A
A
C
C
B
B
C
A
C
C

B
C
C
B
A
B
B
C
C
A
A
C
B
C
C
B
A
B
B
A

[63] , [521] , [4]


[63] , [52] , [41]
[632] , [5] , [41]
[6321] , [5] , [4]
[6321] , [54] , []
[632] , [541] , []
[63] , [541] , [2]
[63] , [54] , [21]
[6] , [543] , [21]
[61] , [543] , [2]
[61] , [5432] , []
[6] , [54321] , []
[] , [54321] , [6]
[] , [5432] , [61]
[2] , [543] , [61]
[21] , [543] , [6]
[21] , [54] , [63]
[2] , [541] , [63]
[] , [541] , [632]
[] , [54] , [6321]
[4] , [5] , [6321]
[41] , [5] , [632]
[41] , [52] , [63]
[4] , [521] , [63]
[43] , [521] , [6]
[43] , [52] , [61]
[432] , [5] , [61]
[4321] , [5] , [6]
[4321] , [] , [65]
[432] , [1] , [65]
[43] , [1] , [652]
[43] , [] , [6521]
[4] , [3] , [6521]
[41] , [3] , [652]
[41] , [32] , [65]
[4] , [321] , [65]
[] , [321] , [654]
[] , [32] , [6541]
[2] , [3] , [6541]
[21] , [3] , [654]
[21] , [] , [6543]
[2] , [1] , [6543]
[] , [1] , [65432]
[] , [] , [654321]

,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,

Move Disc 1
Move Disc 2
Move Disc 1
Move Disc 4
Move Disc 1
Move Disc 2
Move Disc 1
Move Disc 3
Move Disc 1
Move Disc 2
Move Disc 1
Move Disc 6
Move Disc 1
Move Disc 2
Move Disc 1
Move Disc 3
Move Disc 1
Move Disc 2
Move Disc 1
Move Disc 4
Move Disc 1
Move Disc 2
Move Disc 1
Move Disc 3
Move Disc 1
Move Disc 2
Move Disc 1
Move Disc 5
Move Disc 1
Move Disc 2
Move Disc 1
Move Disc 3
Move Disc 1
Move Disc 2
Move Disc 1
Move Disc 4
Move Disc 1
Move Disc 2
Move Disc 1
Move Disc 3
Move Disc 1
Move Disc 2
Move Disc 1
Total Moves

From
From
From
From
From
From
From
From
From
From
From
From
From
From
From
From
From
From
From
From
From
From
From
From
From
From
From
From
From
From
From
From
From
From
From
From
From
From
From
From
From
From
From
= 63

B
B
C
C
A
A
B
A
C
C
A
A
B
B
C
B
A
A
B
B
C
C
A
C
B
B
C
B
A
A
B
A
C
C
A
A
B
B
C
B
A
A
B

To
To
To
To
To
To
To
To
To
To
To
To
To
To
To
To
To
To
To
To
To
To
To
To
To
To
To
To
To
To
To
To
To
To
To
To
To
To
To
To
To
To
To

C
A
A
B
B
C
C
B
A
B
B
C
C
A
A
C
B
C
C
A
A
B
B
A
C
A
A
C
B
C
C
B
A
B
B
C
C
A
A
C
B
C
C

Enter the number of discs (-1 to exit): -1

3. Sample Queue and Regular Sorting


Source Code
#include
#include
#include
#include

<alloc.h>
<stdlib.h>
<string.h>
<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)
{
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;
}
}
}
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: 543126
Displaying Queue: 5 elements
123456
Press any key to continue . . .

4. Sample Stack Implementation


Source Code
#include
#include
#include
#include

<stdio.h>
<alloc.h>
<stdlib.h>
<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
{
* sizeof(int));

s->m_numElements--;
memmove(s->m_data, &s->m_data[1], s->m_numElements

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];
return 0;
}
int size(MyStack *s)
{
return s->m_numElements;
}
int main()
{
MyStack *s1 = malloc(sizeof(MyStack));
int sz, i;
push(s1,
push(s1,
push(s1,
push(s1,
pop(s1);
push(s1,
push(s1,

10);
20);
30);
40);
40);
50);

sz = size(s1);
for(i = 0; i < sz; i++)
{
printf("%d\n", top(s1));
pop(s1);
}
return 0;
}

Output
50
40
30
20
10
Press any key to continue . . .

5.InFix to PostFix Conversion


Source Code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct _MyStack
{
char *m_data;
int m_numElements;
} MyStack;
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;
}
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 == '/')
{
// 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);
printf("PostFix:\t%s\n", postfix);
return 0;
}
Click here to download Turbo C Source Code and Executable
Output
InFix :
a+b*c
PostFix:
abc*+
InFix :
PostFix:

a+b*c/d-e
abc*d/+e-

InFix :
PostFix:

a+b*c/d-e+f*h/i+j-k
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)
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()
{
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
victor
victor
victor
victor
victor
victor
victor
victor

CS
CS
CS
CS
CS
CS
CS
CS
CS

23
23
23
23
23
23
23
23
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
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");
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
Output
Enter First Day of Year(1 - Sunday, 7 - Saturday): 3

Enter 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
Feb 2008
S M T W
1
3 4 5 6 7
10 11 12 13
17 18 19 20
24 25 26 27

T
2
8
14
21
28

F S
9
15 16
22 23
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
1 2 3
4 5 6 7 8 9
11 12 13 14 15
18 19 20 21 22
25 26 27 28 29

F S
10
16 17
23 24
30 31

Jun 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
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
1
3 4 5 6 7
10 11 12 13
17 18 19 20
24 25 26 27
31

T
2
8
14
21
28

F S
9
15 16
22 23
29 30

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
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): 6
Enter Year: 2010

Jan 2010
S M T W
1
3 4 5 6 7
10 11 12 13

T F S
2
8 9
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
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
1 2 3
4 5 6 7 8 9
11 12 13 14 15
18 19 20 21 22
25 26 27 28 29

F S
10
16 17
23 24
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
1 2 3
4 5 6 7 8 9
11 12 13 14 15
18 19 20 21 22
25 26 27 28 29

F S
10
16 17
23 24
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
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)
{
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
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)
{
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;
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
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
Output
Enter Date: 15
Enter Month: 12
Enter 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"
};
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)
{
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;
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 Supported
0
Zero
5
Five
10
Ten
15
Fifteen
19
Nineteen
20
Twenty
21
Twenty One
25
Twenty Five
33
Thirty Three
49
Fourty Nine
50
Fifty
72
Seventy Two
99
Ninety Nine

100
One Hundred
101
One Hundred One
117
One Hundred Seventeen
199
One Hundred Ninety Nine
200
Two Hundred
214
Two Hundred Fourteen
517
Five Hundred Seventeen
589
Five Hundred Eighty Nine
999
Nine Hundred Ninety Nine
1000 One Thousand
1010 One Thousand Ten
1018 One Thousand Eighteen
1200 One Thousand Two Hundred
9890 Nine Thousand Eight Hundred Ninety
10119 Ten Thousand One Hundred Nineteen
13535 Thirteen Thousand Five Hundred Thirty Five
57019 Fifty Seven Thousand Nineteen
99999 Ninety Nine Thousand Nine Hundred Ninety Nine
100000 One Hundred Thousand
100001 Not Supported

10. Sorting Algorithm - Bubble Sort


Source 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])
{
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: 80
Enter [2] element: 60
Enter [3] element: 40
Enter [4] element: 20
Enter [5] element: 10
Enter [6] element: 30
Enter [7] element: 50
Enter [8] element: 70
Before Sorting : 80 60 40 20 10 30 50 70
After iteration 1: 60 40 20 10 30 50 70 80
After iteration 2: 40 20 10 30 50 60 70 80
After iteration 3: 20 10 30 40 50 60 70 80
After iteration 4: 10 20 30 40 50 60 70 80
After iteration 5: 10 20 30 40 50 60 70 80
After iteration 6: 10 20 30 40 50 60 70 80
After iteration 7: 10 20 30 40 50 60 70 80
The numbers in ascending orders are given below:
Sorted [1] element: 10
Sorted [2] element: 20
Sorted [3] element: 30
Sorted [4] element: 40
Sorted [5] element: 50
Sorted [6] element: 60
Sorted [7] element: 70
Sorted [8] element: 80

11. Sorting Algorithm - Insertion Sort


Source 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");
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;
}
Output
Program for Ascending order of Numeric Values using INSERTION SORT
Enter the total number of elements: 8
Enter [1] element: 80
Enter [2] element: 60
Enter [3] element: 40
Enter [4] element: 20
Enter [5] element: 10
Enter [6] element: 30
Enter [7] element: 50
Enter [8] element: 70
Before Sorting : 80 60 40 20 10 30 50 70
After iteration 1: 60 80 40 20 10 30 50 70
After iteration 2: 40 60 80 20 10 30 50 70
After iteration 3: 20 40 60 80 10 30 50 70
After iteration 4: 10 20 40 60 80 30 50 70
After iteration 5: 10 20 30 40 60 80 50 70
After iteration 6: 10 20 30 40 50 60 80 70
After iteration 7: 10 20 30 40 50 60 70 80
The numbers in ascending orders are given below:
Sorted [1] element: 10
Sorted [2] element: 20
Sorted [3] element: 30
Sorted [4] element: 40
Sorted [5] element: 50
Sorted [6] element: 60
Sorted [7] element: 70
Sorted [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++)
{
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 = 01100000

104 = 01101000
112 = 01110000
120 = 01111000
128 = 10000000
13. Binary to Decimal Conversion
Source Code
#include <stdio.h>
#include <conio.h>
#include <dos.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;
}
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;
}
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 = 96
104 = 01101000 = 104
112 = 01110000 = 112
120 = 01111000 = 120
128 = 10000000 = 128
Press any key to continue . . .

14. Factorial of a Number using Recursion


4! means = 1 * 2 * 3 * 4 = 24
5! 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>
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! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800

15. Factorial of a Number with out using Recursion


4! means = 1 * 2 * 3 * 4 = 24
5! 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>
#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;
}
Output
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24

5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800

16. Square Root of a Given Number


Source Code
#include <stdio.h>
#include <math.h>
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;
for(i = 1; i <= 100; i += 3)
{
t = SQRTByGuess(i);
printf("\nSQRT(%d) = %.4lf, %.4lf", i, t, sqrt((double)i));
}
return 0;
}
Output
SQRT(1) = 1.0000, 1.0000
SQRT(4) = 2.0000, 2.0000
SQRT(7) = 2.6458, 2.6458
SQRT(10) = 3.1623, 3.1623
SQRT(13) = 3.6055, 3.6056
SQRT(16) = 4.0000, 4.0000
SQRT(19) = 4.3589, 4.3589
SQRT(22) = 4.6904, 4.6904
SQRT(25) = 5.0000, 5.0000
SQRT(28) = 5.2915, 5.2915
SQRT(31) = 5.5678, 5.5678
SQRT(34) = 5.8309, 5.8310
SQRT(37) = 6.0828, 6.0828
SQRT(40) = 6.3246, 6.3246
SQRT(43) = 6.5574, 6.5574
SQRT(46) = 6.7823, 6.7823
SQRT(49) = 7.0000, 7.0000
SQRT(52) = 7.2111, 7.2111
SQRT(55) = 7.4162, 7.4162
SQRT(58) = 7.6158, 7.6158
SQRT(61) = 7.8102, 7.8102
SQRT(64) = 8.0000, 8.0000
SQRT(67) = 8.1854, 8.1854
SQRT(70) = 8.3666, 8.3666

SQRT(73) = 8.5440, 8.5440


SQRT(76) = 8.7178, 8.7178
SQRT(79) = 8.8882, 8.8882
SQRT(82) = 9.0554, 9.0554
SQRT(85) = 9.2195, 9.2195
SQRT(88) = 9.3808, 9.3808
SQRT(91) = 9.5394, 9.5394
SQRT(94) = 9.6954, 9.6954
SQRT(97) = 9.8489, 9.8489
SQRT(100) = 10.0000, 10.0000
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)
{
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
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));
d = 250000;
printf("sqrt(%.5lf) = %.5lf %.5lf\n", d, MySqrt(d), sqrt(d));
return 0;
}
Output
sqrt(1.00000) = 1.00000 1.00000
sqrt(1235.56979) = 35.15067 35.15067
sqrt(2470.13958) = 49.70049 49.70050
sqrt(3704.70937) = 60.86632 60.86632
sqrt(4939.27916) = 70.28000 70.28001
sqrt(6173.84895) = 78.57384 78.57384
sqrt(7408.41874) = 86.07217 86.07217
sqrt(8642.98853) = 92.96767 92.96767
sqrt(9877.55832) = 99.38590 99.38591
sqrt(11112.12811) = 105.41407 105.41408
sqrt(12346.69790) = 111.11569 111.11570
sqrt(13581.26769) = 116.53869 116.53870
sqrt(14815.83748) = 121.72032 121.72032
sqrt(16050.40727) = 126.69020 126.69020
sqrt(17284.97706) = 131.47234 131.47234
sqrt(18519.54685) = 136.08654 136.08654
sqrt(19754.11664) = 140.54933 140.54934
sqrt(20988.68643) = 144.87472 144.87473
sqrt(22223.25622) = 149.07466 149.07467
sqrt(23457.82601) = 153.15947 153.15948
sqrt(24692.39580) = 157.13814 157.13814
sqrt(25926.96559) = 161.01852 161.01853
sqrt(27161.53538) = 164.80757 164.80757
sqrt(28396.10517) = 168.51143 168.51144
sqrt(29630.67496) = 172.13562 172.13563
sqrt(30865.24475) = 175.68507 175.68507

sqrt(32099.81454) = 179.16421 179.16421


sqrt(33334.38433) = 182.57706 182.57706
sqrt(34568.95412) = 185.92728 185.92728
sqrt(35803.52391) = 189.21819 189.21819
sqrt(37038.09370) = 192.45502 192.45284
sqrt(38272.66349) = 195.63400 195.63400
sqrt(39507.23328) = 198.76426 198.76427
sqrt(40741.80307) = 201.84598 201.84599
sqrt(41976.37286) = 204.88136 204.88136
sqrt(43210.94265) = 207.87241 207.87242
sqrt(44445.51244) = 210.82104 210.82104
sqrt(45680.08223) = 213.73072 213.72899
sqrt(46914.65202) = 216.59790 216.59790
sqrt(48149.22181) = 219.42930 219.42931
sqrt(49383.79160) = 222.22464 222.22464
sqrt(50618.36139) = 224.98524 224.98525
sqrt(51852.93118) = 227.71238 227.71239
sqrt(53087.50097) = 230.40725 230.40725
sqrt(54322.07076) = 233.07232 233.07096
sqrt(55556.64055) = 235.70456 235.70456
sqrt(56791.21034) = 238.30906 238.30906
sqrt(58025.78013) = 240.88540 240.88541
sqrt(59260.34992) = 243.43448 243.43449
sqrt(60494.91971) = 245.95715 245.95715
sqrt(61729.48950) = 248.45420 248.45420
sqrt(62964.05929) = 250.92746 250.92640
sqrt(64198.62908) = 253.37448 253.37448
sqrt(65433.19887) = 255.79913 255.79914
sqrt(66667.76866) = 258.20102 258.20102
sqrt(67902.33845) = 260.58077 260.58077
sqrt(69136.90824) = 262.93898 262.93898
sqrt(70371.47803) = 265.27622 265.27623
sqrt(71606.04782) = 267.59386 267.59306
sqrt(72840.61761) = 269.89001 269.89001
sqrt(74075.18740) = 272.16757 272.16757
sqrt(75309.75719) = 274.42623 274.42623
sqrt(76544.32698) = 276.66645 276.66645
sqrt(77778.89677) = 278.88868 278.88868
sqrt(79013.46656) = 281.09334 281.09334
sqrt(80248.03635) = 283.28142 283.28084
sqrt(81482.60614) = 285.45158 285.45158
sqrt(82717.17593) = 287.60593 287.60594
sqrt(83951.74572) = 289.74427 289.74428
sqrt(85186.31551) = 291.86694 291.86695
sqrt(86420.88530) = 293.97429 293.97429
sqrt(87655.45509) = 296.06663 296.06664

sqrt(88890.02488) = 298.14467 298.14430


sqrt(90124.59467) = 300.20758 300.20759
sqrt(91359.16446) = 302.25678 302.25679
sqrt(92593.73425) = 304.29218 304.29219
sqrt(93828.30404) = 306.31406 306.31406
sqrt(95062.87383) = 308.32267 308.32268
sqrt(96297.44362) = 310.31829 310.31829
sqrt(97532.01341) = 312.30135 312.30116
sqrt(98766.58320) = 314.27151 314.27151
sqrt(100001.15299) = 316.22958 316.22959
sqrt(101235.72278) = 318.17561 318.17562
sqrt(102470.29257) = 320.10981 320.10981
sqrt(103704.86236) = 322.03239 322.03239
sqrt(104939.43215) = 323.94356 323.94356
sqrt(106174.00194) = 325.84381 325.84352
sqrt(107408.57173) = 327.73246 327.73247
sqrt(108643.14152) = 329.61059 329.61059
sqrt(109877.71131) = 331.47807 331.47807
sqrt(111112.28110) = 333.33508 333.33509
sqrt(112346.85089) = 335.18181 335.18182
sqrt(113581.42068) = 337.01842 337.01843
sqrt(114815.99047) = 338.84508 338.84508
sqrt(116050.56026) = 340.66194 340.66194
sqrt(117285.13005) = 342.46916 342.46917
sqrt(118519.69984) = 344.26690 344.26690
sqrt(119754.26963) = 346.05529 346.05530
sqrt(120988.83942) = 347.83450 347.83450
sqrt(122223.40921) = 349.60464 349.60465
sqrt(123457.97900) = 351.36587 351.36588
sqrt(124692.54879) = 353.11832 353.11832
sqrt(125927.11858) = 354.86211 354.86211
sqrt(127161.68837) = 356.59737 356.59738
sqrt(128396.25816) = 358.32423 358.32424
sqrt(129630.82795) = 360.04281 360.04281
sqrt(130865.39774) = 361.75322 361.75323
sqrt(132099.96753) = 363.45559 363.45559
sqrt(133334.53732) = 365.15002 365.15002
sqrt(134569.10711) = 366.83662 366.83662
sqrt(135803.67690) = 368.51550 368.51550
sqrt(137038.24669) = 370.18677 370.18677
sqrt(138272.81648) = 371.85052 371.85053
sqrt(139507.38627) = 373.50687 373.50688
sqrt(140741.95606) = 375.15590 375.15591
sqrt(141976.52585) = 376.79772 376.79773
sqrt(143211.09564) = 378.43355 378.43242
sqrt(144445.66543) = 380.06008 380.06008

sqrt(145680.23522) = 381.68080 381.68080


sqrt(146914.80501) = 383.29467 383.29467
sqrt(148149.37480) = 384.90177 384.90177
sqrt(149383.94459) = 386.50219 386.50219
sqrt(150618.51438) = 388.09601 388.09601
sqrt(151853.08417) = 389.68428 389.68331
sqrt(153087.65396) = 391.26417 391.26417
sqrt(154322.22375) = 392.83867 392.83867
sqrt(155556.79354) = 394.40688 394.40689
sqrt(156791.36333) = 395.96889 395.96889
sqrt(158025.93312) = 397.52475 397.52476
sqrt(159260.50291) = 399.07455 399.07456
sqrt(160495.07270) = 400.61917 400.61836
sqrt(161729.64249) = 402.15624 402.15624
sqrt(162964.21228) = 403.68826 403.68826
sqrt(164198.78207) = 405.21448 405.21449
sqrt(165433.35186) = 406.73498 406.73499
sqrt(166667.92165) = 408.24982 408.24983
sqrt(167902.49144) = 409.75906 409.75907
sqrt(169137.06123) = 411.26343 411.26276
sqrt(170371.63102) = 412.76098 412.76099
sqrt(171606.20081) = 414.25378 414.25379
sqrt(172840.77060) = 415.74123 415.74123
sqrt(174075.34039) = 417.22336 417.22337
sqrt(175309.91018) = 418.70026 418.70026
sqrt(176544.47997) = 420.17196 420.17196
sqrt(177779.04976) = 421.63906 421.63853
sqrt(179013.61955) = 423.10001 423.10001
sqrt(180248.18934) = 424.55646 424.55646
sqrt(181482.75913) = 426.00793 426.00793
sqrt(182717.32892) = 427.45447 427.45448
sqrt(183951.89871) = 428.89613 428.89614
sqrt(185186.46850) = 430.33297 430.33297
sqrt(186421.03829) = 431.76542 431.76503
sqrt(187655.60808) = 433.19234 433.19235
sqrt(188890.17787) = 434.61497 434.61498
sqrt(190124.74766) = 436.03296 436.03297
sqrt(191359.31745) = 437.44635 437.44636
sqrt(192593.88724) = 438.85520 438.85520
sqrt(193828.45703) = 440.25953 440.25953
sqrt(195063.02682) = 441.65967 441.65940
sqrt(196297.59661) = 443.05484 443.05485
sqrt(197532.16640) = 444.44590 444.44591
sqrt(198766.73619) = 445.83263 445.83263
sqrt(200001.30598) = 447.21505 447.21506
sqrt(201235.87577) = 448.59321 448.59322

sqrt(202470.44556) = 449.96716 449.96716


sqrt(203705.01535) = 451.33707 451.33692
sqrt(204939.58514) = 452.70253 452.70253
sqrt(206174.15493) = 454.06404 454.06404
sqrt(207408.72472) = 455.42148 455.42148
sqrt(208643.29451) = 456.77488 456.77488
sqrt(209877.86430) = 458.12428 458.12429
sqrt(211112.43409) = 459.46973 459.46973
sqrt(212347.00388) = 460.81166 460.81125
sqrt(213581.57367) = 462.14886 462.14887
sqrt(214816.14346) = 463.48262 463.48262
sqrt(216050.71325) = 464.81255 464.81256
sqrt(217285.28304) = 466.13869 466.13870
sqrt(218519.85283) = 467.46107 467.46107
sqrt(219754.42262) = 468.77971 468.77972
sqrt(220988.99241) = 470.09466 470.09466
sqrt(222223.56220) = 471.40594 471.40594
sqrt(223458.13199) = 472.71358 472.71358
sqrt(224692.70178) = 474.01761 474.01762
sqrt(225927.27157) = 475.31807 475.31807
sqrt(227161.84136) = 476.61498 476.61498
sqrt(228396.41115) = 477.90837 477.90837
sqrt(229630.98094) = 479.19826 479.19827
sqrt(230865.55073) = 480.48470 480.48470
sqrt(232100.12052) = 481.76770 481.76770
sqrt(233334.69031) = 483.04729 483.04730
sqrt(234569.26010) = 484.32350 484.32351
sqrt(235803.82989) = 485.59636 485.59637
sqrt(237038.39968) = 486.86589 486.86589
sqrt(238272.96947) = 488.13212 488.13212
sqrt(239507.53926) = 489.39507 489.39507
sqrt(240742.10905) = 490.65477 490.65478
sqrt(241976.67884) = 491.91125 491.91125
sqrt(243211.24863) = 493.16452 493.16452
sqrt(244445.81842) = 494.41462 494.41462
sqrt(245680.38821) = 495.66156 495.66157
sqrt(246914.95800) = 496.90538 496.90538
sqrt(248149.52779) = 498.14609 498.14609
sqrt(249384.09758) = 499.38459 499.38372
sqrt(250000.00000) = 500.00000 500.00000
18. Function Keys with bioskey
Source 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
#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:
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 EXE
Output
Press 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 pressed
F1 Key Pressed
F2 Key Pressed
F5 Key Pressed
F6 Key Pressed
F6 Key Pressed
F7 Key Pressed
F8 Key Pressed
F8 Key Pressed
F10 Key Pressed
19. Checking Leap year
Source 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);
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;
}
Output
Enter Beginning Year: 1000
Enter Ending year: 2100
List of Leap Years Between: 1000 and 2100
1004
1028
1052
1076
1104
1128
1152
1176
1200
1224
1248
1272
1296
1324
1348
1372
1396
1424
1448

1008
1032
1056
1080
1108
1132
1156
1180
1204
1228
1252
1276
1304
1328
1352
1376
1404
1428
1452

1012
1036
1060
1084
1112
1136
1160
1184
1208
1232
1256
1280
1308
1332
1356
1380
1408
1432
1456

1016
1040
1064
1088
1116
1140
1164
1188
1212
1236
1260
1284
1312
1336
1360
1384
1412
1436
1460

1020
1044
1068
1092
1120
1144
1168
1192
1216
1240
1264
1288
1316
1340
1364
1388
1416
1440
1464

1024
1048
1072
1096
1124
1148
1172
1196
1220
1244
1268
1292
1320
1344
1368
1392
1420
1444
1468

1472
1496
1524
1548
1572
1596
1620
1644
1668
1692
1720
1744
1768
1792
1820
1844
1868
1892
1920
1944
1968
1992
2016
2040
2064
2088

1476
1504
1528
1552
1576
1600
1624
1648
1672
1696
1724
1748
1772
1796
1824
1848
1872
1896
1924
1948
1972
1996
2020
2044
2068
2092

1480
1508
1532
1556
1580
1604
1628
1652
1676
1704
1728
1752
1776
1804
1828
1852
1876
1904
1928
1952
1976
2000
2024
2048
2072
2096

1484
1512
1536
1560
1584
1608
1632
1656
1680
1708
1732
1756
1780
1808
1832
1856
1880
1908
1932
1956
1980
2004
2028
2052
2076

1488
1516
1540
1564
1588
1612
1636
1660
1684
1712
1736
1760
1784
1812
1836
1860
1884
1912
1936
1960
1984
2008
2032
2056
2080

1492
1520
1544
1568
1592
1616
1640
1664
1688
1716
1740
1764
1788
1816
1840
1864
1888
1916
1940
1964
1988
2012
2036
2060
2084

Press any key to continue . . .


19. Time Span Finding the number of days between two days
Source 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
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)
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)
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);
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;
}
Output
Enter Begin Date: 6
Enter Begin Month: 2
Enter Begin Year: 1978
Enter End Date: 1
Enter End Month: 11
Enter 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: 31

Enter Begin Month: 2


Enter Begin Year: 2010
Enter End Date: 10
Enter End Month: 10
Enter End Year: 2010
Not a valid start date
Press any key to continue . . .
Enter Begin Date: 10
Enter Begin Month: 10
Enter Begin Year: 2010
Enter End Date: 10
Enter End Month: 10
Enter 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;
}
Output
Enter 1 Student Mark: 65
Enter 2 Student Mark: 76
Enter 3 Student Mark: 89
Enter 4 Student Mark: 95
Enter 5 Student Mark: 20
Enter 6 Student Mark: 45
Enter 7 Student Mark: 55
Enter 8 Student Mark: 67
Enter 9 Student Mark: 89
Enter 10 Student Mark: 29
No
Mark Grade
1
65
C+
2
76
B+
3
89
B+
4
95
A+
5
20
F
6
45
C
7
55
C+
8
67
C+
9
89
B+
10
29
F
Press any key to continue . . .
21. randomize, rand and srand functions for generating random numbers
22. Using kbhit, getch and putch functions
23. Using Circle and setcolor, setbkcolor functions
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())
{
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())
{
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.

También podría gustarte