C Programming (Turbo C++ Compiler) Use of break and continue statements
break statement is used to come out the loop.
continue statement is used to continue the loop but skip the execution of the remaining statements in the loop.
These statements are used in any loop statements and switch case statements.
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++;
}
Above sample code has infinite for loop. if i > 60, then break statement will get executed and loop will get terminated. if (i % 2) is false meaning odd number, then the continue statement will skip the remainder of the statement. In this case, eventcount will not get incremented.
C Programming (Turbo C++ Compiler) Use of #define macro
#define is a macro and it is used widely in C whenever required. All #define values get replaced with actual values after compilation. Then one might ask a question, why do we need #define macro? The answer is program clarity and ease of maintenance.
Another place #define are used widely is with project configuration. For example, You can have different code for _DEBUG and NDEBUG (release) mode configuration.
you can check like,
#if defined(_DEBUG)
printf("working under debug mode");
#endif
Look the following simple example.
int _tmain(int argc, TCHAR* argv[])
{
int arrayData[10];
int CloneData[10];
for(int i = 0; i < 10; i++)
{
scand("%d",&arrayData[i]);
}
for(int i = 0; i < 10; i++)
{
CloneData[i] = arrayData[i];
}
for(int i = 0; i < 10; i++)
{
printf("%d\n", CloneData[i]);
}
int a = 10 + 20 + 30;
int b = a;
return 0;
}
The number 10 is used in 6 places in the function out of which 5 places are the same purpose indicating the number of elements. If we have to change the number of elements it to 20, then we have to make changes in 5 places out of 6 places where 10 is used.
If we have used #define macro, it would be very easy to change. #define is used for clarity and ease of program maintenance.
#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;
}
C Programming (Turbo C++ Compiler) Enumerations
There is a very clear difference between #define macro and enumerations, event it may confuse some people. enumeration is not a macro and it stays even after compilation. enums are used when there is logical grouping of elements are necessary.
The first element in the enum has default value set to 0, if there is no value assigned. The next elements has follow the simple formula of the value of the previous element plus 1.
Look at the sample code and output. It is easy to understand.
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 . . .
C Programming (Turbo C++ Compiler) - Switch Case Statement
We can write the entire code with if else statements and with out using switch case statement at all. Then why do we need switch case statements? The answer is for program clarity and ease of maintenance.
If we have 2 - 4 cases, then we can use if else statements. If we have more number of cases, then still you can proceed with if else, however it is better to use switch case statements.
switch(key) - switch will take key as an argument. It can be of numeric integer value only (both positive and negative numbers). It can not accept any floating point numbers or strings. It can accept enums as they are treated as integers.
Note: If you do not use break statement after case block, then it will continue executing the next case.
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;
}
};
}
C Programming (Turbo C++ Compiler) - Static Variables For Counting
Variables can be declared in stack or heap or static. Static variables means the memory is allocated statically and its life time is throughout the program execution time.
If a variable is allocated on the stack, we can see that stack size is increasing. If a variable is allocated on the heap (example malloc in C), we can see that heap size if increasing.
If I allocate a variable of 100 KB in static, which size will increase? Stack or Heap? Both are not correct. Your size of the .EXE file will increase..! This might be a surprise to many programmers in the begining. Similarly global variables are also allocated like static variables and its life time is throughout the program execution time.
Example for static variabales allocation is given below:
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;
}
Ouput
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 . . .
C Programming (Turbo C++ Compiler) - Static Global Variables
Variables can be declared in stack or heap or static. Static variables means the memory is allocated statically and its life time is throughout the program execution time.
If a variable is allocated on the stack, we can see that stack size is increasing. If a variable is allocated on the heap (example malloc in C), we can see that heap size if increasing.
If I allocate a variable of 100 KB in static, which size will increase? Stack or Heap? Both are not correct. Your size of the .EXE file will increase..! This might be a surprise to many programmers in the begining. Similarly global variables are also allocated like static variables and its life time is throughout the program execution time.
IsEntered is a static global variable and can be used by any function defined in the file.
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
C Programming (Turbo C++ Compiler) - Static Variables
Variables can be declared in stack or heap or static. Static variables means the memory is allocated statically and its life time is throughout the program execution time.
If a variable is allocated on the stack, we can see that stack size is increasing. If a variable is allocated on the heap (example malloc in C), we can see that heap size if increasing.
If I allocate a variable of 100 KB in static, which size will increase? Stack or Heap? Both are not correct. Your size of the .EXE file will increase..! This might be a surprise to many programmers in the begining. Similarly global variables are also allocated like static variables and its life time is throughout the program execution time.
Example for static variabales allocation is given below:
#include <iostream.h>
static char msg[] = "Welcome to my static function";
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);
}
C Programming (Turbo C++ Compiler) - Factorial of a Number using Recursion
We can write a program to find the factorial of a given number using recursion and 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.
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
C Programming (Turbo C++ Compiler) - Binary to Decimal Conversion
Lets try writing a C program to convert a binary number to decimal number with out using any string functions. The key here is the number you are going to convert will be in decimal number only even it is a binary number representing 0s and 1s.
If we have to Convert Binary Number 101 to a decimal number(5), then input will be 101 in decimal form only.
If we have to Convert Binary Number 1010 to a decimal number(10), then input will be 1010 in decimal form only.
It is not that difficult since the coding for the core logic will be just 6 lines. Refer to the function int ConvertBinary2Decimal(int bin).
The complete program and test run output are given below:
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 . . .
C Programming (Turbo C++ Compiler) Decimal to Binary Conversion
Lets try writing a C program to convert a decimal number to integer with out using any string functions. The key here is the number you are going to convert will be in decimal number only even it is a binary number representing 0s and 1s.
If we have to Convert Decimal Number 5 to a binary number, then output will be 101 in decimal form only.
If we have to Convert Decimal Number 10 to a binary number, then output will be 1010 in decimal form only.
It is not that difficult since the coding for the core logic will be just 6 lines. Refer to the function int ConvertDecimal2Binary(int dec).
The complete program and test run output are given below:
Sample 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
C Programming (Turbo C++ Compiler) - Convert Numbers to Text (Words)
There might be some cases where we need to display the numbers as text. For example, given the input as 115 and output would be One Hundred Fifteen.
I have given here the code to display the numbers upto 100,000. If you want more limit, you can keep extending the program.
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)
(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
C Programming (Turbo C++ Compiler) - Static Functions
Static functions in a file restricts the access level to the functions on that file only.
Example for static function is given below:
#include <stdio.h>
static const char* GetWelcomeMessage()
{
static char msg[] = "Welcome to my static function";
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
}
C Programming (Turbo C++ Compiler) - Sorting Algorithm - Bubble Sort
We often using sorting algorithm to sort numbers and strings. Also we have many sorting algorithms. I have explained here on how bubble sort algorithm works. Look at the yellow color high lighting section on output to understand how algorithm works after each iteration.
The complete program and test run output are given below:
Sample 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
C Programming (Turbo C++ Compiler) Sorting Algorithm - Insertion Sort
We often using sorting algorithm to sort numbers and strings. Also we have many sorting algorithms. I have explained here on how Insertion sort algorithm works. Look at the yellow color high lighting section on output to understand how algorithm works after each iteration.
The complete program and test run output are given below:
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
C Programming (Turbo C++ Compiler) - Factorial of a Number with out using Recursion
We can write a program to find the factorial of a given number using recursion and 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.
Sample 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
C Programming (Turbo C++ Compiler) - Checking Leap year
I have given here the source code for checking whether the given year is a leap year or not.
First Rule: The year divisible by 4 is a leap year.
Second Rule: If the year is divisible by 100, then it is not a leap year. But If the year is divisible by 400, then it is a 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 1008 1012 1016 1020 1024
1028 1032 1036 1040 1044 1048
1052 1056 1060 1064 1068 1072
1076 1080 1084 1088 1092 1096
1104 1108 1112 1116 1120 1124
1128 1132 1136 1140 1144 1148
1152 1156 1160 1164 1168 1172
1176 1180 1184 1188 1192 1196
1200 1204 1208 1212 1216 1220
1224 1228 1232 1236 1240 1244
1248 1252 1256 1260 1264 1268
1272 1276 1280 1284 1288 1292
1296 1304 1308 1312 1316 1320
1324 1328 1332 1336 1340 1344
1348 1352 1356 1360 1364 1368
1372 1376 1380 1384 1388 1392
1396 1404 1408 1412 1416 1420
1424 1428 1432 1436 1440 1444
1448 1452 1456 1460 1464 1468
1472 1476 1480 1484 1488 1492
1496 1504 1508 1512 1516 1520
1524 1528 1532 1536 1540 1544
1548 1552 1556 1560 1564 1568
1572 1576 1580 1584 1588 1592
1596 1600 1604 1608 1612 1616
1620 1624 1628 1632 1636 1640
1644 1648 1652 1656 1660 1664
1668 1672 1676 1680 1684 1688
1692 1696 1704 1708 1712 1716
1720 1724 1728 1732 1736 1740
1744 1748 1752 1756 1760 1764
1768 1772 1776 1780 1784 1788
1792 1796 1804 1808 1812 1816
1820 1824 1828 1832 1836 1840
1844 1848 1852 1856 1860 1864
1868 1872 1876 1880 1884 1888
1892 1896 1904 1908 1912 1916
1920 1924 1928 1932 1936 1940
1944 1948 1952 1956 1960 1964
1968 1972 1976 1980 1984 1988
1992 1996 2000 2004 2008 2012
2016 2020 2024 2028 2032 2036
2040 2044 2048 2052 2056 2060
2064 2068 2072 2076 2080 2084
2088 2092 2096
C Programming (Turbo C++ Compiler) Displaying ASCII Characters On Screen
I have given here a simple program that can display all 255 characters in one screen.
Source Code
// Printing ASCII characters
#include <conio.h>
#include <process.h>
#include <dos.h>
#include <stdio.h>
int main()
{
unsigned char ch ;
int x, y;
clrscr();
for(unsigned char ch = 0; ch < 255; ch++)
{
printf("%3d = %c\n", ch, ch);
}
printf("\n\n");
return 0;
}
Output
0 =
1 =
2 =
3 =
4 =
5 =
6 =
7 =
8 =
9 =
10 =
11 =
12 =
13 =
14 =
15 =
16 =
17 =
18 =
19 =
20 =
21 =
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 = þ
C Programming (Turbo C++ Compiler) - Square Root of a Given Number
You can solve the problem in two ways with out using the library function sqrt(...) defined in math.h header file.
Method 1 - Like binary search, have a minimum and maximum possible values. Do the square operation and compare the result. Then adjust minimum or maximum until we find the correct sqrt of the given number. NOTE: This is NOT a perfect square root and it has got accuracy of 4 decimal points. Method 1 is explained on this page.
Method 2 - The traditional way of doing with out calculator or any assumption. It will be perfect square root up to N number of decimal points meaning the limitation of float and double. (I Will update this topic very shortly with sample code).
Sample 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
C Programming (Turbo C++ Compiler) - Check Perfect Square
Write a Program to check whether a num is perfect square or not, 25, 36, 49 are perfect squares.
The idea here is to find out the square root of given number and convert it into an integer and do the square to check whether it is a perfect square or NOT. If the number falls between the square of min and square of max, then it is not a perfect square.
Look at the sample code and output.
Sample 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
Press any key to continue . . .
C Programming (Turbo C++ Compiler) - Generating Prime Numbers
I have given here the source code in Turbo C for generating the 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 3 5 7 11 13
17 19 23 29 31 37
41 43 47 53 59 61
67 71 73 79 83 89
97 101 103 107 109 113
127 131 137 139 149 151
157 163 167 173 179 181
191 193 197 199 211 223
227 229 233 239 241 251
257 263 269 271 277 281
283 293 307 311 313 317
331 337 347 349 353 359
367 373 379 383 389 397
401 409 419 421 431 433
439 443 449 457 461 463
467 479 487 491 499 503
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
C Programming (Turbo C++ Compiler) - Getting Prime Factors of a Number
Given a number, we can find out what would be the prime factors of the number. But it is not easy to find out since we have to go through couple of iteratons.
Prime Factor For 9360 = 13 * 5 * 3 * 3 * 2 * 2 * 2 * 2
Note that all the numbers 13, 5, 3, 2 are prime numbers.
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 = 0;
int i = 0;
printf("Enter a Number: ");
scanf("%d", &num1);
count = GetPrimeFactors(num1, result);
printf("Prime Factor For %d = ", num1);
for(i = 0; i < count; i++)
{
printf("%d", result[i]);
if(i != count - 1)
printf(" * ");
}
printf("\n");
return 0;
}
Output
Enter a Number: 9360
Prime Factors For 9360 = 13 * 5 * 3 * 3 * 2 * 2 * 2 * 2
Press any key to continue . . .
Enter a Number: 48125
Prime Factors For 48125 = 11 * 7 * 5 * 5 * 5 * 5
Press any key to continue . . .
C Programming (Turbo C++ Compiler) - Counting Characters, Words and lines from a file or string buffer
Here I have given the source code to count the number of Characters, Words and lines from a file or string buffer.
GetWordCount function is written in C language and tested with turbo c++ compiler.
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");
FILE *istream = fopen(srcFileName,
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
Chars: 127
Words: 16
Lines: 2
Press any key to continue . . .
C Programming (Turbo C++ Compiler) Fahrenheit Celsius Converter
I have given here a simple program to convert Fahrenheit to Celsius and vice versa.
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, 248);
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 = -2.2222 °C
28.0000 °C = 82.4000 °F
Press any key to continue .
C Programming (Turbo C++ Compiler) - Terminate and Stay Resident Program (TSR) Timer Clock Sample
I have given here a sample program for TSR which stands for Terminate and Stay Resident. It is easy to implement but you need to know about interrupt service routines and their functions.
Timer.EXE -i option will install the timer.
Timer.EXE -u option will uninstall the timer.
Source Code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dos.h>
#include <conio.h>
#include <bios.h>
#define INTR 0X1C
#ifdef __cplusplus
#define __CPPARGS ...
#else
#define __CPPARGS
#endif
char far *scr=(char far*)0xB0008000L;
void interrupt ( *oldhandler)(__CPPARGS);
int count=0;
char hbuf[6];
char mbuf[6];
char sbuf[6];
struct time t;
void interrupt handler(__CPPARGS)
{
char far *p = 0;
gettime(&t);
hbuf[0] = '0' + t.ti_hour / 10;
hbuf[1] = '0' + t.ti_hour % 10;
mbuf[0] = '0' + t.ti_min / 10;
mbuf[1] = '0' + t.ti_min % 10;
sbuf[0] = '0' + t.ti_sec / 10;
sbuf[1] = '0' + t.ti_sec % 10;
p = scr;
*p++ = hbuf[0];
*p++ = 0x4f;
*p++ = hbuf[1];
*p++ = 0x4f;
*p++ = ':';
*p++ = 0x4f;
*p++ = mbuf[0];
*p++ = 0x4f;
*p++ = mbuf[1];
*p++ = 0x4f;
*p++ = ':';
*p++ = 0x4f;
*p++ = sbuf[0];
*p++ = 0x4f;
*p++ = sbuf[1];
*p++ = 0x4f;
oldhandler();
}
int main(int argc, char *argv[])
{
if(argc <= 1)
{
printf("Syntax: Timer -I (for Install)\n");
printf("Syntax: Timer -U (for Uninstall)\n");
return 0;
}
if(argv[1][1] == 'I' || argv[1][1] == 'i')
{
printf("Installing...\n");
oldhandler = getvect(INTR);
setvect(INTR, handler);
setvect(32, oldhandler);
printf("Done\n");
}
else
{
printf("Uninstalling...\n");
oldhandler = getvect(32);
setvect(INTR, oldhandler);
printf("Done\n");
}
return 0;
}
C Programming (Turbo C++ Compiler) - Greatest Common Divisor (GCD) and Least Common Multiple (LCM)
I have given here the source code for calculating Greatest Common Divisor(GCD) and Least Common Multiple (LCM). I used the logic of prime number factors and common prime factors between the given two numbers to find the GCD. Once you know GCD, finding LCM is easy with the formula
LCM(a,b) = (a * b)/ GCD(a,b)
Source Code
#include <stdio.h>
#define MAX_SIZE 15000
typedef enum _boolean
{
false = 0, true = 1
} bool;
bool IsPrimeNumber(int num)
{
bool bPrime = true;
int factor = num / 2;
int i = 0;
for(i = 2; i <= factor; i++)
{
if( (num % i) == 0)
bPrime = false;
}
return bPrime;
}
int GetPrimeFactors(int num, int *arrResult)
{
int count = 0;
int arr[MAX_SIZE];
int i = 0;
int 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;
}
int GetCommonPrimeFactors(int *arr1, int count1, int *arr2, int count2, int *arrResult)
{
int idx = 0;
int i = 0;
int j = 0;
for(i = 0; i < count1; i++)
{
for(j = 0; j < count2; j++)
{
if(arr2[j] < 0)
continue;
if(arr1[i] == arr2[j])
{
arrResult[idx++] = arr1[i];
arr1[i] = arr2[j] = -1;
}
}
}
return idx;
}
int GetGCD(int num1, int num2, bool disp)
{
int arr1[MAX_SIZE], arr2[MAX_SIZE], arrResult[MAX_SIZE];
int i, j, k, countResult;
int gcd = 0;
int count1 = GetPrimeFactors(num1, arr1);
int count2 = GetPrimeFactors(num2, arr2);
if(disp == true)
{
printf("\nNumber1 %d =", num1);
for(i = 0; i < count1; i++)
{
printf("%d ", arr1[i]);
if(i != count1 - 1)
printf(" * ");
}
printf("\nNumber2 $d =", num2);
for(j = 0; j < count2; j++)
{
printf("%d ", arr2[j]);
if(j != count2 - 1)
printf(" * ");
}
}
countResult = GetCommonPrimeFactors(arr1, count1, arr2, count2, arrResult);
if(disp == true)
printf("\nGCD(%d,%d) = ", num1, num2);
gcd = 1;
for(k = 0; k < countResult; k++)
{
if(disp == true)
{
printf("%d", arrResult[k]);
if(k != countResult - 1)
printf(" * ");
}
gcd *= arrResult[k];
}
if(disp == true)
printf("\n\n");
return gcd;
}
int GetLCM(int num1, long num2)
{
printf("%d", (num1 * num2));
printf("\n");
return (num1 * num2) / GetGCD(num1, num2, false);
}
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, true);
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
Number1 10 = 5 * 2
Number2 135 = 5 * 3 * 3 * 3
GCD(10,135) = 5
GCD(10,135) = 5
LCM(10,135) = 270
Press any key to continue . . .
Enter First Number: 455
Enter Second Number: 2015
Number1 455 = 13 * 7 * 5
Number2 2015 = 31 * 13 * 5
GCD(455,2015) = 13 * 5
GCD(455,2015) = 65
LCM(455,2015) = 14105
Press any key to continue . . .
C Programming (Turbo C++ Compiler) - Function Keys with bioskey
We can use function keys F1, F2, F3, etc and any control keys and Up Arrow / Down Arrow in Turbo C.
We have to efficient function call bioskey rather than getch(). bioskey(1) to read whether a key is pressed or not. bioskey(0) to read the actual key.
Source code and Sample output is given below.
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;
}
}
}
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
C Programming (Turbo C++ Compiler) - Time Span Finding the number of days between two days
I have given here the source code for the time span.
The logic for finding leap year is applying the following two rules,
First Rule: The year divisible by 4 is a leap year.
Second Rule: If the year is divisible by 100, then it is not a leap year. But If the year is divisible by 400, then it is a leap year.
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 . . .
C Programming (Turbo C++ Compiler) - Simple Student Grading Logic
I have given here a simple student grading by using if conditions and pointer assignment.
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 . . .
C Programming (Turbo C++ Compiler) Graphics - Starting with Graphics
I have given a sample program on how to turn on graphics mode in Turbo C in MS-DOS 16 bit application.
If you get EGAVGA.BGI error in the output, then it means the file is not placed in the path.
Look at the sample code and output.
Source Code
#include <stdio.h>
#include <graphics.h>
#include <stdlib.h>
#include <conio.h>
#include <bios.h>
void main()
{
int grd, grm;
int num, xpos, ypos, i, j, index;
detectgraph(&grd,&grm);
initgraph(&grd, &grm, "");
if( graphresult() != 0)
{
printf("Unable to find Graphics driver");
return;
}
num = getmaxcolor();
settextjustify(CENTER_TEXT, CENTER_TEXT);
xpos = getmaxx() / 2;
ypos = getmaxy() / 2;
setbkcolor(BLUE);
setcolor(WHITE);
rectangle(1,1,getmaxx() - 1, getmaxy() - 1);
for(j = 1; j <= 11; j++)
{
circle(30, j * 40, 18);
circle(getmaxx() - 30, j * 40, 18);
}
index = 0;
for(i = BLUE + 1; i < num; i++)
{
setcolor(i);
outtextxy(xpos,50 + (index++ * 30),"Welcome to http://www.softwareandfinance.com");
}
getch();
closegraph();
}
Output
The background color is solid BLUE.
Left and Right column with 11 circles in white color.
Welcome to http://itechstudents.weebly.com/ in different colors.
Everything will fit into a while color rectangle.
C Programming (Turbo C++ Compiler) Graphics - Blink Characters and Words
Here is the graphics program that can display the word in different colors. It uses simple for loop and outtextxy along with setcolor commands.
Look at the source code and output.
Source Code
#include <dos.h>
#include <stdio.h>
#include <graphics.h>
#include <stdlib.h>
#include <conio.h>
void main()
{
int grd, grm;
int bgcolor, xmax, ymax,color,j;
char buf[] = "http://www.softwareandfinance.com";
detectgraph(&grd,&grm);
initgraph(&grd, &grm, "");
bgcolor = BLUE;
setbkcolor(bgcolor);
xmax = getmaxx();
ymax = getmaxy();
setcolor(WHITE);
rectangle(0,0,xmax,ymax);
settextstyle(DEFAULT_FONT, HORIZ_DIR, 2);
color = GREEN;
for(j = 0; j <= 10; j++)
{
if( (j % 2) == 0)
{
setcolor(color++);
outtextxy(20, 220, buf);
delay(1000);
if(color > WHITE)
color = GREEN;
}
else
{
setcolor(bgcolor);
outtextxy(20, 220, buf);
delay(500);
}
}
getch();
closegraph();
}
Output
http://itechstudents.weebly.com/ will display in different colors.
C Programming (Turbo C++ Compiler) Graphics - Drawing Circles with Pixels
This graphics program displays circles by plotting the pixel by pixel. It uses the formula xend = x + r cos(angle) and yend = y + r sin(angle).
Look at the source code and output.
Source Code
#include <stdio.h>
#include <graphics.h>
#include <stdlib.h>
#include <conio.h>
#include <bios.h>
#include <math.h>
void DrawCircle(int x, int y, int r, int color)
{
static const double PI = 3.1415926535;
double i, angle, x1, y1;
for(i = 0; i < 360; i += 0.1)
{
angle = i;
x1 = r * cos(angle * PI / 180);
y1 = r * sin(angle * PI / 180);
putpixel(x + x1, y + y1, color);
}
}
void main()
{
int grd, grm, i;
int color, xmax, ymax;
detectgraph(&grd,&grm);
initgraph(&grd, &grm, "");
color = GREEN;
setbkcolor(BLUE);
xmax = getmaxx();
ymax = getmaxy();
setcolor(WHITE);
rectangle(0,0,xmax,ymax);
for(i = 0; i < 230; i += 10)
{
DrawCircle(320, 240, i, color++);
if(color > WHITE)
color = GREEN;
}
getch();
closegraph();
}
Output
Many circles in different colors will be shown pixel by pixel.
C Programming (Turbo C++ Compiler) Graphics - Move Object using getimage and putimage
Here is the graphics program that can move an object from one location to another using getimage and putimage functions.
Look at the source code and output.
Source Code
#include <stdio.h>
#include <string.h>
#include <alloc.h>
#include <graphics.h>
#include <stdlib.h>
#include <conio.h>
#include <bios.h>
#include <math.h>
#include <dos.h>
void draw_pixelbackground()
{
int i;
int xpos, ypos, color;
int xmax = getmaxx();
int ymax = getmaxy();
setbkcolor(BLUE);
setcolor(WHITE);
rectangle(0,0,xmax, ymax);
for(i = 0; i < 5000; i++)
{
xpos = rand() % xmax;
ypos = rand() % ymax;
color = rand() % 12;
putpixel(xpos, ypos, color);
}
}
void draw_object(int left, int top, int right, int bottom)
{
rectangle(left, top, right, bottom);
line(left, top, right, bottom);
line(left, bottom, right, top);
}
void move_object(int left, int top, int right, int bottom,int destx, int desty)
{
int i,j;
int width = right - left;
int height = bottom - top;
long size = imagesize(left, top, right, bottom);
void far *buffer1 = farmalloc(size);
void far *buffer2 = farmalloc(size);
getimage(left, top, right, bottom, buffer1);
for(i = left; i <= destx; i += 10)
{
getimage(i, top, i + width, top + height, buffer2);
putimage(i, top, buffer1, COPY_PUT);
delay(100);
if(i > left)
{
putimage(i, top, buffer2, COPY_PUT);
delay(10);
}
}
for(j = top; j <= desty; j += 10)
{
getimage(destx, j, destx + width, j + height, buffer2);
putimage(destx, j, buffer1, COPY_PUT);
delay(100);
if(j > top && j < desty)
{
putimage(destx, j, buffer2, COPY_PUT);
delay(10);
}
}
{
// Move Again back to original position
for(i = destx; i >= left; i -= 10)
{
getimage(i, desty, i + width, desty + height, buffer2);
putimage(i, desty, buffer1, COPY_PUT);
delay(100);
if(i > left)
{
putimage(i, desty, buffer2, COPY_PUT);
delay(10);
}
}
for(j = desty; j > top; j -= 10)
{
getimage(left, j, left + width, j + height, buffer2);
putimage(left, j, buffer1, COPY_PUT);
delay(100);
if(j > top && j < desty)
{
putimage(left, j, buffer2, COPY_PUT);
delay(10);
}
}
}
}
void main()
{
int grd, grm;
detectgraph(&grd,&grm);
initgraph(&grd, &grm, "");
draw_pixelbackground();
draw_object(10,30,100, 70);
move_object(10,30,100, 70, 530, 430);
getch();
closegraph();
}
Output
C Programming (Turbo C++ Compiler) Graphics - Plot Sin Cos and Tan Series
Here is the program that can draw the SIN, COS and TAN series. Each series will be drawn in different colors and legends are also shown.
Source Code
#include <stdio.h>
#include <graphics.h>
#include <stdlib.h>
#include <conio.h>
#include <bios.h>
#include <math.h>
void main()
{
int grd, grm;
int xmax, ymax, m;
int margin, width, height;
double legendxpos, legendypos, factor;
static const double PI = 3.1415926535;
int bPlotSinSeries = 1;
int bPlotCosSeries = 1;
int bPlotTanSeries = 1;
char buf[32];
int xpos, ypos;
double i, value;
detectgraph(&grd,&grm);
initgraph(&grd, &grm, "");
setbkcolor(BLUE);
xmax = getmaxx();
ymax = getmaxy();
setcolor(WHITE);
rectangle(0,0,xmax,ymax);
margin = 50;
width = getmaxx() - margin;
height = getmaxy() - margin;
rectangle(0 + margin / 2, 0 + margin / 2, width + margin / 2, height + margin / 2);
line(0 + margin / 2, margin / 2 + height / 2,
width + margin / 2, margin / 2 + height / 2);
legendypos = margin;
legendxpos = margin;
if(bPlotSinSeries == 1)
{
for(i = 0; i <= 720.01; i += 0.01)
{
value = sin(i * PI / 180);
value += 1.0;
ypos = value / 2 * height + margin / 2;
xpos = i / 720.0 * width + margin / 2;
putpixel(xpos, ypos, YELLOW);
m = i;
if( (m % 90) == 0)
{
line(xpos, margin / 2 + height / 2 - 5,
xpos, margin / 2 + height / 2 + 5);
sprintf(buf, "%d", m);
outtextxy(xpos - 10, margin / 2 + height / 2 + 10, buf);
}
}
setcolor(YELLOW);
outtextxy(legendxpos, legendypos, "SIN Series - Yellow Color");
legendypos += 20;
}
if(bPlotCosSeries == 1)
{
for(i = 0; i <= 720.01; i += 0.01)
{
value = cos(i * PI / 180);
value += 1.0;
ypos = value / 2 * height + margin / 2;
xpos = i / 720.0 * width + margin / 2;
putpixel(xpos, ypos, GREEN);
m = i;
if( (m % 90) == 0)
{
line(xpos, margin / 2 + height / 2 - 5,
xpos, margin / 2 + height / 2 + 5);
sprintf(buf, "%d", m);
outtextxy(xpos - 10, margin / 2 + height / 2 + 10, buf);
}
}
setcolor(GREEN);
outtextxy(legendxpos, legendypos, "COS Series - Green Color");
legendypos += 20;
}
if(bPlotTanSeries == 1)
{
factor = 10; // Don't use this factor, it is only for drawing purpose.
for(i = 0; i <= 720.01; i += 0.01)
{
value = tan(i * PI / 180);
if(value > factor)
value = factor;
if(value < -factor)
value = -factor;
value += factor;
ypos = value / (factor * 2) * height + margin / 2;
xpos = i / 720.0 * width + margin / 2;
putpixel(xpos, ypos, WHITE);
m = i;
if( (m % 90) == 0)
{
line(xpos, margin / 2 + height / 2 - 5,
xpos, margin / 2 + height / 2 + 5);
sprintf(buf, "%d", m);
outtextxy(xpos - 10, margin / 2 + height / 2 + 10, buf);
}
}
setcolor(WHITE);
outtextxy(legendxpos, legendypos, "TAN Series - WHITE Color");
legendypos += 20;
}
getch();
closegraph();
}
Output
SIN, COS and TAN series will be shown on the screen in different colors.
break statement is used to come out the loop.
continue statement is used to continue the loop but skip the execution of the remaining statements in the loop.
These statements are used in any loop statements and switch case statements.
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++;
}
Above sample code has infinite for loop. if i > 60, then break statement will get executed and loop will get terminated. if (i % 2) is false meaning odd number, then the continue statement will skip the remainder of the statement. In this case, eventcount will not get incremented.
C Programming (Turbo C++ Compiler) Use of #define macro
#define is a macro and it is used widely in C whenever required. All #define values get replaced with actual values after compilation. Then one might ask a question, why do we need #define macro? The answer is program clarity and ease of maintenance.
Another place #define are used widely is with project configuration. For example, You can have different code for _DEBUG and NDEBUG (release) mode configuration.
you can check like,
#if defined(_DEBUG)
printf("working under debug mode");
#endif
Look the following simple example.
int _tmain(int argc, TCHAR* argv[])
{
int arrayData[10];
int CloneData[10];
for(int i = 0; i < 10; i++)
{
scand("%d",&arrayData[i]);
}
for(int i = 0; i < 10; i++)
{
CloneData[i] = arrayData[i];
}
for(int i = 0; i < 10; i++)
{
printf("%d\n", CloneData[i]);
}
int a = 10 + 20 + 30;
int b = a;
return 0;
}
The number 10 is used in 6 places in the function out of which 5 places are the same purpose indicating the number of elements. If we have to change the number of elements it to 20, then we have to make changes in 5 places out of 6 places where 10 is used.
If we have used #define macro, it would be very easy to change. #define is used for clarity and ease of program maintenance.
#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;
}
C Programming (Turbo C++ Compiler) Enumerations
There is a very clear difference between #define macro and enumerations, event it may confuse some people. enumeration is not a macro and it stays even after compilation. enums are used when there is logical grouping of elements are necessary.
The first element in the enum has default value set to 0, if there is no value assigned. The next elements has follow the simple formula of the value of the previous element plus 1.
Look at the sample code and output. It is easy to understand.
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 . . .
C Programming (Turbo C++ Compiler) - Switch Case Statement
We can write the entire code with if else statements and with out using switch case statement at all. Then why do we need switch case statements? The answer is for program clarity and ease of maintenance.
If we have 2 - 4 cases, then we can use if else statements. If we have more number of cases, then still you can proceed with if else, however it is better to use switch case statements.
switch(key) - switch will take key as an argument. It can be of numeric integer value only (both positive and negative numbers). It can not accept any floating point numbers or strings. It can accept enums as they are treated as integers.
Note: If you do not use break statement after case block, then it will continue executing the next case.
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;
}
};
}
C Programming (Turbo C++ Compiler) - Static Variables For Counting
Variables can be declared in stack or heap or static. Static variables means the memory is allocated statically and its life time is throughout the program execution time.
If a variable is allocated on the stack, we can see that stack size is increasing. If a variable is allocated on the heap (example malloc in C), we can see that heap size if increasing.
If I allocate a variable of 100 KB in static, which size will increase? Stack or Heap? Both are not correct. Your size of the .EXE file will increase..! This might be a surprise to many programmers in the begining. Similarly global variables are also allocated like static variables and its life time is throughout the program execution time.
Example for static variabales allocation is given below:
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;
}
Ouput
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 . . .
C Programming (Turbo C++ Compiler) - Static Global Variables
Variables can be declared in stack or heap or static. Static variables means the memory is allocated statically and its life time is throughout the program execution time.
If a variable is allocated on the stack, we can see that stack size is increasing. If a variable is allocated on the heap (example malloc in C), we can see that heap size if increasing.
If I allocate a variable of 100 KB in static, which size will increase? Stack or Heap? Both are not correct. Your size of the .EXE file will increase..! This might be a surprise to many programmers in the begining. Similarly global variables are also allocated like static variables and its life time is throughout the program execution time.
IsEntered is a static global variable and can be used by any function defined in the file.
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
C Programming (Turbo C++ Compiler) - Static Variables
Variables can be declared in stack or heap or static. Static variables means the memory is allocated statically and its life time is throughout the program execution time.
If a variable is allocated on the stack, we can see that stack size is increasing. If a variable is allocated on the heap (example malloc in C), we can see that heap size if increasing.
If I allocate a variable of 100 KB in static, which size will increase? Stack or Heap? Both are not correct. Your size of the .EXE file will increase..! This might be a surprise to many programmers in the begining. Similarly global variables are also allocated like static variables and its life time is throughout the program execution time.
Example for static variabales allocation is given below:
#include <iostream.h>
static char msg[] = "Welcome to my static function";
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);
}
C Programming (Turbo C++ Compiler) - Factorial of a Number using Recursion
We can write a program to find the factorial of a given number using recursion and 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.
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
C Programming (Turbo C++ Compiler) - Binary to Decimal Conversion
Lets try writing a C program to convert a binary number to decimal number with out using any string functions. The key here is the number you are going to convert will be in decimal number only even it is a binary number representing 0s and 1s.
If we have to Convert Binary Number 101 to a decimal number(5), then input will be 101 in decimal form only.
If we have to Convert Binary Number 1010 to a decimal number(10), then input will be 1010 in decimal form only.
It is not that difficult since the coding for the core logic will be just 6 lines. Refer to the function int ConvertBinary2Decimal(int bin).
The complete program and test run output are given below:
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 . . .
C Programming (Turbo C++ Compiler) Decimal to Binary Conversion
Lets try writing a C program to convert a decimal number to integer with out using any string functions. The key here is the number you are going to convert will be in decimal number only even it is a binary number representing 0s and 1s.
If we have to Convert Decimal Number 5 to a binary number, then output will be 101 in decimal form only.
If we have to Convert Decimal Number 10 to a binary number, then output will be 1010 in decimal form only.
It is not that difficult since the coding for the core logic will be just 6 lines. Refer to the function int ConvertDecimal2Binary(int dec).
The complete program and test run output are given below:
Sample 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
C Programming (Turbo C++ Compiler) - Convert Numbers to Text (Words)
There might be some cases where we need to display the numbers as text. For example, given the input as 115 and output would be One Hundred Fifteen.
I have given here the code to display the numbers upto 100,000. If you want more limit, you can keep extending the program.
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)
(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
C Programming (Turbo C++ Compiler) - Static Functions
Static functions in a file restricts the access level to the functions on that file only.
Example for static function is given below:
#include <stdio.h>
static const char* GetWelcomeMessage()
{
static char msg[] = "Welcome to my static function";
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
}
C Programming (Turbo C++ Compiler) - Sorting Algorithm - Bubble Sort
We often using sorting algorithm to sort numbers and strings. Also we have many sorting algorithms. I have explained here on how bubble sort algorithm works. Look at the yellow color high lighting section on output to understand how algorithm works after each iteration.
The complete program and test run output are given below:
Sample 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
C Programming (Turbo C++ Compiler) Sorting Algorithm - Insertion Sort
We often using sorting algorithm to sort numbers and strings. Also we have many sorting algorithms. I have explained here on how Insertion sort algorithm works. Look at the yellow color high lighting section on output to understand how algorithm works after each iteration.
The complete program and test run output are given below:
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
C Programming (Turbo C++ Compiler) - Factorial of a Number with out using Recursion
We can write a program to find the factorial of a given number using recursion and 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.
Sample 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
C Programming (Turbo C++ Compiler) - Checking Leap year
I have given here the source code for checking whether the given year is a leap year or not.
First Rule: The year divisible by 4 is a leap year.
Second Rule: If the year is divisible by 100, then it is not a leap year. But If the year is divisible by 400, then it is a 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 1008 1012 1016 1020 1024
1028 1032 1036 1040 1044 1048
1052 1056 1060 1064 1068 1072
1076 1080 1084 1088 1092 1096
1104 1108 1112 1116 1120 1124
1128 1132 1136 1140 1144 1148
1152 1156 1160 1164 1168 1172
1176 1180 1184 1188 1192 1196
1200 1204 1208 1212 1216 1220
1224 1228 1232 1236 1240 1244
1248 1252 1256 1260 1264 1268
1272 1276 1280 1284 1288 1292
1296 1304 1308 1312 1316 1320
1324 1328 1332 1336 1340 1344
1348 1352 1356 1360 1364 1368
1372 1376 1380 1384 1388 1392
1396 1404 1408 1412 1416 1420
1424 1428 1432 1436 1440 1444
1448 1452 1456 1460 1464 1468
1472 1476 1480 1484 1488 1492
1496 1504 1508 1512 1516 1520
1524 1528 1532 1536 1540 1544
1548 1552 1556 1560 1564 1568
1572 1576 1580 1584 1588 1592
1596 1600 1604 1608 1612 1616
1620 1624 1628 1632 1636 1640
1644 1648 1652 1656 1660 1664
1668 1672 1676 1680 1684 1688
1692 1696 1704 1708 1712 1716
1720 1724 1728 1732 1736 1740
1744 1748 1752 1756 1760 1764
1768 1772 1776 1780 1784 1788
1792 1796 1804 1808 1812 1816
1820 1824 1828 1832 1836 1840
1844 1848 1852 1856 1860 1864
1868 1872 1876 1880 1884 1888
1892 1896 1904 1908 1912 1916
1920 1924 1928 1932 1936 1940
1944 1948 1952 1956 1960 1964
1968 1972 1976 1980 1984 1988
1992 1996 2000 2004 2008 2012
2016 2020 2024 2028 2032 2036
2040 2044 2048 2052 2056 2060
2064 2068 2072 2076 2080 2084
2088 2092 2096
C Programming (Turbo C++ Compiler) Displaying ASCII Characters On Screen
I have given here a simple program that can display all 255 characters in one screen.
Source Code
// Printing ASCII characters
#include <conio.h>
#include <process.h>
#include <dos.h>
#include <stdio.h>
int main()
{
unsigned char ch ;
int x, y;
clrscr();
for(unsigned char ch = 0; ch < 255; ch++)
{
printf("%3d = %c\n", ch, ch);
}
printf("\n\n");
return 0;
}
Output
0 =
1 =
2 =
3 =
4 =
5 =
6 =
7 =
8 =
9 =
10 =
11 =
12 =
13 =
14 =
15 =
16 =
17 =
18 =
19 =
20 =
21 =
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 = þ
C Programming (Turbo C++ Compiler) - Square Root of a Given Number
You can solve the problem in two ways with out using the library function sqrt(...) defined in math.h header file.
Method 1 - Like binary search, have a minimum and maximum possible values. Do the square operation and compare the result. Then adjust minimum or maximum until we find the correct sqrt of the given number. NOTE: This is NOT a perfect square root and it has got accuracy of 4 decimal points. Method 1 is explained on this page.
Method 2 - The traditional way of doing with out calculator or any assumption. It will be perfect square root up to N number of decimal points meaning the limitation of float and double. (I Will update this topic very shortly with sample code).
Sample 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
C Programming (Turbo C++ Compiler) - Check Perfect Square
Write a Program to check whether a num is perfect square or not, 25, 36, 49 are perfect squares.
The idea here is to find out the square root of given number and convert it into an integer and do the square to check whether it is a perfect square or NOT. If the number falls between the square of min and square of max, then it is not a perfect square.
Look at the sample code and output.
Sample 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
Press any key to continue . . .
C Programming (Turbo C++ Compiler) - Generating Prime Numbers
I have given here the source code in Turbo C for generating the 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 3 5 7 11 13
17 19 23 29 31 37
41 43 47 53 59 61
67 71 73 79 83 89
97 101 103 107 109 113
127 131 137 139 149 151
157 163 167 173 179 181
191 193 197 199 211 223
227 229 233 239 241 251
257 263 269 271 277 281
283 293 307 311 313 317
331 337 347 349 353 359
367 373 379 383 389 397
401 409 419 421 431 433
439 443 449 457 461 463
467 479 487 491 499 503
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
C Programming (Turbo C++ Compiler) - Getting Prime Factors of a Number
Given a number, we can find out what would be the prime factors of the number. But it is not easy to find out since we have to go through couple of iteratons.
Prime Factor For 9360 = 13 * 5 * 3 * 3 * 2 * 2 * 2 * 2
Note that all the numbers 13, 5, 3, 2 are prime numbers.
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 = 0;
int i = 0;
printf("Enter a Number: ");
scanf("%d", &num1);
count = GetPrimeFactors(num1, result);
printf("Prime Factor For %d = ", num1);
for(i = 0; i < count; i++)
{
printf("%d", result[i]);
if(i != count - 1)
printf(" * ");
}
printf("\n");
return 0;
}
Output
Enter a Number: 9360
Prime Factors For 9360 = 13 * 5 * 3 * 3 * 2 * 2 * 2 * 2
Press any key to continue . . .
Enter a Number: 48125
Prime Factors For 48125 = 11 * 7 * 5 * 5 * 5 * 5
Press any key to continue . . .
C Programming (Turbo C++ Compiler) - Counting Characters, Words and lines from a file or string buffer
Here I have given the source code to count the number of Characters, Words and lines from a file or string buffer.
GetWordCount function is written in C language and tested with turbo c++ compiler.
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");
FILE *istream = fopen(srcFileName,
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
Chars: 127
Words: 16
Lines: 2
Press any key to continue . . .
C Programming (Turbo C++ Compiler) Fahrenheit Celsius Converter
I have given here a simple program to convert Fahrenheit to Celsius and vice versa.
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, 248);
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 = -2.2222 °C
28.0000 °C = 82.4000 °F
Press any key to continue .
C Programming (Turbo C++ Compiler) - Terminate and Stay Resident Program (TSR) Timer Clock Sample
I have given here a sample program for TSR which stands for Terminate and Stay Resident. It is easy to implement but you need to know about interrupt service routines and their functions.
Timer.EXE -i option will install the timer.
Timer.EXE -u option will uninstall the timer.
Source Code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dos.h>
#include <conio.h>
#include <bios.h>
#define INTR 0X1C
#ifdef __cplusplus
#define __CPPARGS ...
#else
#define __CPPARGS
#endif
char far *scr=(char far*)0xB0008000L;
void interrupt ( *oldhandler)(__CPPARGS);
int count=0;
char hbuf[6];
char mbuf[6];
char sbuf[6];
struct time t;
void interrupt handler(__CPPARGS)
{
char far *p = 0;
gettime(&t);
hbuf[0] = '0' + t.ti_hour / 10;
hbuf[1] = '0' + t.ti_hour % 10;
mbuf[0] = '0' + t.ti_min / 10;
mbuf[1] = '0' + t.ti_min % 10;
sbuf[0] = '0' + t.ti_sec / 10;
sbuf[1] = '0' + t.ti_sec % 10;
p = scr;
*p++ = hbuf[0];
*p++ = 0x4f;
*p++ = hbuf[1];
*p++ = 0x4f;
*p++ = ':';
*p++ = 0x4f;
*p++ = mbuf[0];
*p++ = 0x4f;
*p++ = mbuf[1];
*p++ = 0x4f;
*p++ = ':';
*p++ = 0x4f;
*p++ = sbuf[0];
*p++ = 0x4f;
*p++ = sbuf[1];
*p++ = 0x4f;
oldhandler();
}
int main(int argc, char *argv[])
{
if(argc <= 1)
{
printf("Syntax: Timer -I (for Install)\n");
printf("Syntax: Timer -U (for Uninstall)\n");
return 0;
}
if(argv[1][1] == 'I' || argv[1][1] == 'i')
{
printf("Installing...\n");
oldhandler = getvect(INTR);
setvect(INTR, handler);
setvect(32, oldhandler);
printf("Done\n");
}
else
{
printf("Uninstalling...\n");
oldhandler = getvect(32);
setvect(INTR, oldhandler);
printf("Done\n");
}
return 0;
}
C Programming (Turbo C++ Compiler) - Greatest Common Divisor (GCD) and Least Common Multiple (LCM)
I have given here the source code for calculating Greatest Common Divisor(GCD) and Least Common Multiple (LCM). I used the logic of prime number factors and common prime factors between the given two numbers to find the GCD. Once you know GCD, finding LCM is easy with the formula
LCM(a,b) = (a * b)/ GCD(a,b)
Source Code
#include <stdio.h>
#define MAX_SIZE 15000
typedef enum _boolean
{
false = 0, true = 1
} bool;
bool IsPrimeNumber(int num)
{
bool bPrime = true;
int factor = num / 2;
int i = 0;
for(i = 2; i <= factor; i++)
{
if( (num % i) == 0)
bPrime = false;
}
return bPrime;
}
int GetPrimeFactors(int num, int *arrResult)
{
int count = 0;
int arr[MAX_SIZE];
int i = 0;
int 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;
}
int GetCommonPrimeFactors(int *arr1, int count1, int *arr2, int count2, int *arrResult)
{
int idx = 0;
int i = 0;
int j = 0;
for(i = 0; i < count1; i++)
{
for(j = 0; j < count2; j++)
{
if(arr2[j] < 0)
continue;
if(arr1[i] == arr2[j])
{
arrResult[idx++] = arr1[i];
arr1[i] = arr2[j] = -1;
}
}
}
return idx;
}
int GetGCD(int num1, int num2, bool disp)
{
int arr1[MAX_SIZE], arr2[MAX_SIZE], arrResult[MAX_SIZE];
int i, j, k, countResult;
int gcd = 0;
int count1 = GetPrimeFactors(num1, arr1);
int count2 = GetPrimeFactors(num2, arr2);
if(disp == true)
{
printf("\nNumber1 %d =", num1);
for(i = 0; i < count1; i++)
{
printf("%d ", arr1[i]);
if(i != count1 - 1)
printf(" * ");
}
printf("\nNumber2 $d =", num2);
for(j = 0; j < count2; j++)
{
printf("%d ", arr2[j]);
if(j != count2 - 1)
printf(" * ");
}
}
countResult = GetCommonPrimeFactors(arr1, count1, arr2, count2, arrResult);
if(disp == true)
printf("\nGCD(%d,%d) = ", num1, num2);
gcd = 1;
for(k = 0; k < countResult; k++)
{
if(disp == true)
{
printf("%d", arrResult[k]);
if(k != countResult - 1)
printf(" * ");
}
gcd *= arrResult[k];
}
if(disp == true)
printf("\n\n");
return gcd;
}
int GetLCM(int num1, long num2)
{
printf("%d", (num1 * num2));
printf("\n");
return (num1 * num2) / GetGCD(num1, num2, false);
}
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, true);
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
Number1 10 = 5 * 2
Number2 135 = 5 * 3 * 3 * 3
GCD(10,135) = 5
GCD(10,135) = 5
LCM(10,135) = 270
Press any key to continue . . .
Enter First Number: 455
Enter Second Number: 2015
Number1 455 = 13 * 7 * 5
Number2 2015 = 31 * 13 * 5
GCD(455,2015) = 13 * 5
GCD(455,2015) = 65
LCM(455,2015) = 14105
Press any key to continue . . .
C Programming (Turbo C++ Compiler) - Function Keys with bioskey
We can use function keys F1, F2, F3, etc and any control keys and Up Arrow / Down Arrow in Turbo C.
We have to efficient function call bioskey rather than getch(). bioskey(1) to read whether a key is pressed or not. bioskey(0) to read the actual key.
Source code and Sample output is given below.
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;
}
}
}
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
C Programming (Turbo C++ Compiler) - Time Span Finding the number of days between two days
I have given here the source code for the time span.
The logic for finding leap year is applying the following two rules,
First Rule: The year divisible by 4 is a leap year.
Second Rule: If the year is divisible by 100, then it is not a leap year. But If the year is divisible by 400, then it is a leap year.
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 . . .
C Programming (Turbo C++ Compiler) - Simple Student Grading Logic
I have given here a simple student grading by using if conditions and pointer assignment.
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 . . .
C Programming (Turbo C++ Compiler) Graphics - Starting with Graphics
I have given a sample program on how to turn on graphics mode in Turbo C in MS-DOS 16 bit application.
If you get EGAVGA.BGI error in the output, then it means the file is not placed in the path.
Look at the sample code and output.
Source Code
#include <stdio.h>
#include <graphics.h>
#include <stdlib.h>
#include <conio.h>
#include <bios.h>
void main()
{
int grd, grm;
int num, xpos, ypos, i, j, index;
detectgraph(&grd,&grm);
initgraph(&grd, &grm, "");
if( graphresult() != 0)
{
printf("Unable to find Graphics driver");
return;
}
num = getmaxcolor();
settextjustify(CENTER_TEXT, CENTER_TEXT);
xpos = getmaxx() / 2;
ypos = getmaxy() / 2;
setbkcolor(BLUE);
setcolor(WHITE);
rectangle(1,1,getmaxx() - 1, getmaxy() - 1);
for(j = 1; j <= 11; j++)
{
circle(30, j * 40, 18);
circle(getmaxx() - 30, j * 40, 18);
}
index = 0;
for(i = BLUE + 1; i < num; i++)
{
setcolor(i);
outtextxy(xpos,50 + (index++ * 30),"Welcome to http://www.softwareandfinance.com");
}
getch();
closegraph();
}
Output
The background color is solid BLUE.
Left and Right column with 11 circles in white color.
Welcome to http://itechstudents.weebly.com/ in different colors.
Everything will fit into a while color rectangle.
C Programming (Turbo C++ Compiler) Graphics - Blink Characters and Words
Here is the graphics program that can display the word in different colors. It uses simple for loop and outtextxy along with setcolor commands.
Look at the source code and output.
Source Code
#include <dos.h>
#include <stdio.h>
#include <graphics.h>
#include <stdlib.h>
#include <conio.h>
void main()
{
int grd, grm;
int bgcolor, xmax, ymax,color,j;
char buf[] = "http://www.softwareandfinance.com";
detectgraph(&grd,&grm);
initgraph(&grd, &grm, "");
bgcolor = BLUE;
setbkcolor(bgcolor);
xmax = getmaxx();
ymax = getmaxy();
setcolor(WHITE);
rectangle(0,0,xmax,ymax);
settextstyle(DEFAULT_FONT, HORIZ_DIR, 2);
color = GREEN;
for(j = 0; j <= 10; j++)
{
if( (j % 2) == 0)
{
setcolor(color++);
outtextxy(20, 220, buf);
delay(1000);
if(color > WHITE)
color = GREEN;
}
else
{
setcolor(bgcolor);
outtextxy(20, 220, buf);
delay(500);
}
}
getch();
closegraph();
}
Output
http://itechstudents.weebly.com/ will display in different colors.
C Programming (Turbo C++ Compiler) Graphics - Drawing Circles with Pixels
This graphics program displays circles by plotting the pixel by pixel. It uses the formula xend = x + r cos(angle) and yend = y + r sin(angle).
Look at the source code and output.
Source Code
#include <stdio.h>
#include <graphics.h>
#include <stdlib.h>
#include <conio.h>
#include <bios.h>
#include <math.h>
void DrawCircle(int x, int y, int r, int color)
{
static const double PI = 3.1415926535;
double i, angle, x1, y1;
for(i = 0; i < 360; i += 0.1)
{
angle = i;
x1 = r * cos(angle * PI / 180);
y1 = r * sin(angle * PI / 180);
putpixel(x + x1, y + y1, color);
}
}
void main()
{
int grd, grm, i;
int color, xmax, ymax;
detectgraph(&grd,&grm);
initgraph(&grd, &grm, "");
color = GREEN;
setbkcolor(BLUE);
xmax = getmaxx();
ymax = getmaxy();
setcolor(WHITE);
rectangle(0,0,xmax,ymax);
for(i = 0; i < 230; i += 10)
{
DrawCircle(320, 240, i, color++);
if(color > WHITE)
color = GREEN;
}
getch();
closegraph();
}
Output
Many circles in different colors will be shown pixel by pixel.
C Programming (Turbo C++ Compiler) Graphics - Move Object using getimage and putimage
Here is the graphics program that can move an object from one location to another using getimage and putimage functions.
Look at the source code and output.
Source Code
#include <stdio.h>
#include <string.h>
#include <alloc.h>
#include <graphics.h>
#include <stdlib.h>
#include <conio.h>
#include <bios.h>
#include <math.h>
#include <dos.h>
void draw_pixelbackground()
{
int i;
int xpos, ypos, color;
int xmax = getmaxx();
int ymax = getmaxy();
setbkcolor(BLUE);
setcolor(WHITE);
rectangle(0,0,xmax, ymax);
for(i = 0; i < 5000; i++)
{
xpos = rand() % xmax;
ypos = rand() % ymax;
color = rand() % 12;
putpixel(xpos, ypos, color);
}
}
void draw_object(int left, int top, int right, int bottom)
{
rectangle(left, top, right, bottom);
line(left, top, right, bottom);
line(left, bottom, right, top);
}
void move_object(int left, int top, int right, int bottom,int destx, int desty)
{
int i,j;
int width = right - left;
int height = bottom - top;
long size = imagesize(left, top, right, bottom);
void far *buffer1 = farmalloc(size);
void far *buffer2 = farmalloc(size);
getimage(left, top, right, bottom, buffer1);
for(i = left; i <= destx; i += 10)
{
getimage(i, top, i + width, top + height, buffer2);
putimage(i, top, buffer1, COPY_PUT);
delay(100);
if(i > left)
{
putimage(i, top, buffer2, COPY_PUT);
delay(10);
}
}
for(j = top; j <= desty; j += 10)
{
getimage(destx, j, destx + width, j + height, buffer2);
putimage(destx, j, buffer1, COPY_PUT);
delay(100);
if(j > top && j < desty)
{
putimage(destx, j, buffer2, COPY_PUT);
delay(10);
}
}
{
// Move Again back to original position
for(i = destx; i >= left; i -= 10)
{
getimage(i, desty, i + width, desty + height, buffer2);
putimage(i, desty, buffer1, COPY_PUT);
delay(100);
if(i > left)
{
putimage(i, desty, buffer2, COPY_PUT);
delay(10);
}
}
for(j = desty; j > top; j -= 10)
{
getimage(left, j, left + width, j + height, buffer2);
putimage(left, j, buffer1, COPY_PUT);
delay(100);
if(j > top && j < desty)
{
putimage(left, j, buffer2, COPY_PUT);
delay(10);
}
}
}
}
void main()
{
int grd, grm;
detectgraph(&grd,&grm);
initgraph(&grd, &grm, "");
draw_pixelbackground();
draw_object(10,30,100, 70);
move_object(10,30,100, 70, 530, 430);
getch();
closegraph();
}
Output
C Programming (Turbo C++ Compiler) Graphics - Plot Sin Cos and Tan Series
Here is the program that can draw the SIN, COS and TAN series. Each series will be drawn in different colors and legends are also shown.
Source Code
#include <stdio.h>
#include <graphics.h>
#include <stdlib.h>
#include <conio.h>
#include <bios.h>
#include <math.h>
void main()
{
int grd, grm;
int xmax, ymax, m;
int margin, width, height;
double legendxpos, legendypos, factor;
static const double PI = 3.1415926535;
int bPlotSinSeries = 1;
int bPlotCosSeries = 1;
int bPlotTanSeries = 1;
char buf[32];
int xpos, ypos;
double i, value;
detectgraph(&grd,&grm);
initgraph(&grd, &grm, "");
setbkcolor(BLUE);
xmax = getmaxx();
ymax = getmaxy();
setcolor(WHITE);
rectangle(0,0,xmax,ymax);
margin = 50;
width = getmaxx() - margin;
height = getmaxy() - margin;
rectangle(0 + margin / 2, 0 + margin / 2, width + margin / 2, height + margin / 2);
line(0 + margin / 2, margin / 2 + height / 2,
width + margin / 2, margin / 2 + height / 2);
legendypos = margin;
legendxpos = margin;
if(bPlotSinSeries == 1)
{
for(i = 0; i <= 720.01; i += 0.01)
{
value = sin(i * PI / 180);
value += 1.0;
ypos = value / 2 * height + margin / 2;
xpos = i / 720.0 * width + margin / 2;
putpixel(xpos, ypos, YELLOW);
m = i;
if( (m % 90) == 0)
{
line(xpos, margin / 2 + height / 2 - 5,
xpos, margin / 2 + height / 2 + 5);
sprintf(buf, "%d", m);
outtextxy(xpos - 10, margin / 2 + height / 2 + 10, buf);
}
}
setcolor(YELLOW);
outtextxy(legendxpos, legendypos, "SIN Series - Yellow Color");
legendypos += 20;
}
if(bPlotCosSeries == 1)
{
for(i = 0; i <= 720.01; i += 0.01)
{
value = cos(i * PI / 180);
value += 1.0;
ypos = value / 2 * height + margin / 2;
xpos = i / 720.0 * width + margin / 2;
putpixel(xpos, ypos, GREEN);
m = i;
if( (m % 90) == 0)
{
line(xpos, margin / 2 + height / 2 - 5,
xpos, margin / 2 + height / 2 + 5);
sprintf(buf, "%d", m);
outtextxy(xpos - 10, margin / 2 + height / 2 + 10, buf);
}
}
setcolor(GREEN);
outtextxy(legendxpos, legendypos, "COS Series - Green Color");
legendypos += 20;
}
if(bPlotTanSeries == 1)
{
factor = 10; // Don't use this factor, it is only for drawing purpose.
for(i = 0; i <= 720.01; i += 0.01)
{
value = tan(i * PI / 180);
if(value > factor)
value = factor;
if(value < -factor)
value = -factor;
value += factor;
ypos = value / (factor * 2) * height + margin / 2;
xpos = i / 720.0 * width + margin / 2;
putpixel(xpos, ypos, WHITE);
m = i;
if( (m % 90) == 0)
{
line(xpos, margin / 2 + height / 2 - 5,
xpos, margin / 2 + height / 2 + 5);
sprintf(buf, "%d", m);
outtextxy(xpos - 10, margin / 2 + height / 2 + 10, buf);
}
}
setcolor(WHITE);
outtextxy(legendxpos, legendypos, "TAN Series - WHITE Color");
legendypos += 20;
}
getch();
closegraph();
}
Output
SIN, COS and TAN series will be shown on the screen in different colors.