C Programming Module2 Tenouk
C Programming Module2 Tenouk
PROGRAM STRUCTURE
AND BASIC DATA TYPES
Abilities
2.1 A Program
- C / C++ programs consist of functions, one of which must be main(). Every C / C++ program begins
execution at the main() function.
- The keywords used in C / C++ have special meaning to the compiler. The programmer can’t use these
words for identifiers such as variable names.
- The following table is a list of keywords used in ANSI C.
Keyword Description
An automatic storage class for automatic variable. Normally not explicitly
auto
used.
Used to force an immediate exit from while, for, do loops and switch-
break
case statement.
case A label used together with switch statement for selection.
char A single byte data type, capable holding one character in the character set.
A qualifier used to declare variable to specify that its value will not be
const
changed.
Related to break statement, causes the next iteration of the enclosing for,
continue
while or do loop to begin. Applies only to loops, not to switch statement.
An optional label used together with case label. When there is no case
default
expression matched, default label expression will be executed.
Used in do-while loop, repetition where the test condition is at the end of
do
the loop body.
double A double-precision floating point.
elif #elif. Preprocessor statement for else-if.
else Used together with if (if-else) for conditional execution.
endif #endif. Preprocessor statement for end-if.
Used in declaring enumeration constant. Enumeration is a list of constant
enum
integer values.
External storage class. External to all function or globally accessible variable.
extern
Variable declared with extern can be accessed by name by any function.
float Used when declaring floating-point data type.
for Used in the repetition loop.
goto A program control statement for branching/jumping to.
Used for conditional execution, standalone or with else. #if used for
if
conditional inclusion of the preprocessor directive.
ifdef #ifdef, if defined; test whether a name is defined.
ifndef #ifndef, if not defined; test whether a name is not defined.
int An integer data type, the size of normal integers.
A qualifier (long and short) applied to basic data types. short – 16 bits,
long
long-32 bits, int either 16 or 32 bits.
www.tenouk.com Page 1 of 29
Another storage class specifier. Used to advise the compiler to place the
register variables in machine’s processor register instead of machine’s memory but it is
not a mandatory for the compiler.
Used to return a value from the called function to its caller. Any expression
can follow return. The calling function is free to ignore the returned value
return
and can be no expression after return (no value is returned). For main(),
return will pass to system environment, operating system if there is no error.
A qualifier (long and short) applied to basic data types. short – 16 bits,
short
long-32 bits, int either 16 or 32 bits.
A qualifier may be applied to char or any integer. For example, signed
int. Including the positive and negative integers. For example, integer
signed
equivalent range for signed char is -128 and 127 (2’s complement
machine).
An operator. Shows the number of bytes (occupied or) required to store an
sizeof object of the type of its operand. The operand is either an expression or a
parenthesized type name.
A storage class specifier. Local variables (internal variables) that retain their
values throughout the lifetime of the program. Also can be applied to external
variables as well as functions. Functions declared as static, its name is
static
invisible outside of the file in which it is declared. For an external variables or
functions, static will limit the scope of that objects to the rest of the source file
being compiled.
A structure specifier for an object that consist a sequence of named members of
struct
various types.
Used in a selection program control. Used together with case label to test
switch whether an expression matches one of a member of case’s constant integer
and branches accordingly.
typedef Used to create new data type name.
A variable that may hold (at different time) objects of different types and
union
sizes. If at the same time, use struct.
A qualifier may be applied to char or any integer. For example, unsigned
unsigned int. Including the positive integers or zero. For example, integer equivalent
range for unsigned char is 0 and 255.
Data type that specifies an empty set of values or nonexistence value but
void pointers (pointers to void) may be assigned to and from pointers of type
void *.
A qualifier used to force an implementation to suppress optimization that could
volatile
otherwise occur.
while Used for conditional loop execution. Normally together with the do.
- The following table is a list of C++ keywords; most of the keywords will be used in Tutorial #2 and #3.
www.tenouk.com Page 2 of 29
false The Boolean value of "false".
Declare a function or class to be a friend of another class providing
friend
the access of all the data members and member function of a class.
Asking the compiler that certain function should be generated or
inline
executed inline instead of function call.
The mutable keyword overrides any enclosing const statement. A
mutable
mutable member of a const object can be modified.
namespace Keyword used to create a new scope.
Dynamically allocate a memory object on a free store, that is an
new extra memory that available to the program at execution time and
automatically determine the object's size in term of byte.
operator Declare an overloaded operator.
A class member accessible to member functions and friend
private
functions of the private member's class.
protected members may be accessed by member functions of
protected
derived classes and friends of derived classes.
public A class member accessible to any function.
Replaces casts for conversions that are unsafe or implementation
reinterpret_cast
dependent.
static_cast Converts types between related types.
template Declare how to construct class or function using variety of types.
A pointer implicitly declared in every non-static member
this function of a class. It points to the object for which this member
function has been invoked.
Transfer control to an exception handler or terminate program
throw
execution if appropriate handler cannot be located.
true The Boolean value of "true".
Creates a block that containing a set of statements that may
generate exceptions, and enables exception handling for any
try
exceptions generated (normally used together with throw and
catch).
typeid Gets run-time identification of types and expressions.
Used to qualify an identifier of a template as being a type instead of
typename
a value.
using Used to import a namespace into the current scope.
virtual Declare a virtual function.
wchar_t Used to declare wide character variables.
- One way to master C/C++ programming is to master the keywords and usages :o).
2.3 Identifiers
1. The first character of an identifier must be a letter, an underscore ( _ ) also counts as a letter.
2. The blank or white space character is not permitted in an identifier.
3. Can be any length. Internal identifier (do not have the external linkage) such as preprocessor
macro names at least the first 31 characters are significant, also implementation dependent.
4. Reserved words/keywords and characters such as main and # also cannot be used.
2.4 Variables
www.tenouk.com Page 3 of 29
- Initializing a variable means, give a value to the variable, that is the variable’s initial value and can be
changed later on.
- Variable name are said to be lvalue (left value) because they can be used on the left side of an
assignment operator.
- Constant are said to be rvalue (right value) because they only can be used on the right side of an
assignment operator. For example:
x = 20;
x is lvalue, 20 is rvalue.
- Note that lvalue can also be used as rvalue, but not vice versa.
- Notation used in C / C++ can be Hungarian Notation or CamelCase Notation. The information for
these notations can be found HERE.
int x, y, z;
short number_one;
long Type0fCar;
unsigned int positive_number;
char Title;
float commission, yield;
General form:
data_type variable_list;
Note the blank space.
int m, n = 10;
char * ptr = "TESTING";
float total, rate = 0.5;
char user_response = ‘n’;
char color[7] = "green";
int m, n;
float total, rate;
char user_response;
char color[7];
n = 20;
rate = 4.5;
user_response = ‘n’;
color = "green";
- Why we need to learn data types? Every variable used in program hold data, and every data must have
their own type. It is the way how we can ‘measure’ the variable’s data value as exist in the real world.
Further more by knowing the data range, we can use data efficiently in our program in term of memory
management (storage allocation) aspects.
- For example, no need for us to reserve a lot of storage space such as a long data type if we just want
to store a small amount of data, let say, int data type.
- Every data in C / C++ has their own type. There are basic data type and derived data type. This
Module deals with basic data type.
- There are two kinds of basic data type: integral (integer value) and floating (real number). char data
type classified in integral type.
- Derived data types will be presented in another Module. Derived data type including the aggregate
data type is constructed from basic data type such as arrays, functions, pointers, structures, unions and
other user defined data types. Basic data type (int, char and float) and their variation are shown
in Table 2.3. 2.4 and 2.5.
www.tenouk.com Page 4 of 29
Data type Keyword Bits Range
integer int 16 -32768 to 32767
long 32 -4294967296 to 4294967295
long
integer
short 8 -128 to 127
short
integer
unsigned 16 0 to 65535
unsigned
integer
character char 8 0 to 255
floating 32 approximately 6 digits of
float
point precision
double 64 approximately 12 digits
floating double of precision
point
- The following tables list the sizes and resulting ranges of the data types based on IBM PC compatible
system. For 64 bits, the size and range may not valid anymore :o).
www.tenouk.com Page 5 of 29
1.1104932 precision)
- We are very familiar with integer constants that are the base 10 numbers, 0 – 9. There are other bases
such as 16, 8 and 2 numbers that we will encounter when learning programming.
- Octal integer constants must start with 0 followed by any combination of digits taken from 0 through
7. For examples:
- Hexadecimal integer constants must start with 0x or 0X (capital hexadecimal) followed by any
combination of digits taken from 0 through 9 and uppercase letters A through F. For examples:
- The literal data-type qualifiers bring different means for same constant data. For example:
▪ 75 mean the integer 75, but 75L represents the long integer 75.
▪ 75U means the unsigned integer 75.
▪ 75UL means the unsigned long integer 75.
▪ 4.12345 mean the double value 4.12345, but 4.12345F represents the float value
4.12345.
- The backslash (\) is called an escape character. When the backslash is encountered, function such as
printf() for example, will look ahead at the next character and combines it with the backslash to
form an escape sequence, used in functions printf() and scanf().
- Table 2.6 is the list of the escape sequence.
- For general C++ escape sequences are given in the following table. Besides using the sequence, we
also can use their value representation (in hexadecimal) for example \0x0A for newline.
www.tenouk.com Page 6 of 29
\XH any H=a string of hex digits
2.7 Constants
- A character constant is any character enclosed between two single quotation marks (' and ').
- When several characters are enclosed between two double quotation marks (" and "), it is called a
string.
- Examples:
Character constants:
"Name: "
"Type of Fruit"
"Day: "
" "
- You will learn other aggregate or derived data type specifiers such as struct, union, enum and
typedef in other Modules or in the program examples.
- During the program development, you may encounter the situations where you need to convert to the
different data type from previously declared variables, as well as having mixed data type in one
expression.
- For example, let say you have declared the following variables:
- But in the middle of your program you encountered the following expression:
- This expression has mixed data type, int and float. The value of the average will be truncated, and
it is not accurate anymore. Many compilers will generate warning and some do not, but the output will
be inaccurate.
- C provides the unary (take one operand only) typecast operator to accomplish this task. The previous
expression can be re written as
- This (float) is called type cast operator, which create temporary floating-point copy of the total
operand. The construct for this typecast operator is formed by placing parentheses around a data type
name as:
- In an expression containing the data types int and float for example, the ANSI C standard specifies
that copies of int operands are made and promoted to float.
www.tenouk.com Page 7 of 29
- The cast operator normally used together with the conversion specifiers heavily used with printf()
and scanf(). C’s type promotion rules specify how types can be converted to other types without
losing the data accuracy.
- The promotion rules automatically apply to expressions containing values of two or more different data
type in mixed type expression. The type of each value in a mixed-type expression is automatically
promoted to the highest type in the expression.
- Implicitly, actually, only a temporary version of each new value (type) is created and used for the
mixed-type expression, the original value with original type still remain unchanged.
- Table 2.8 list the data types in order from highest to lowest type with printf and scanf conversion
specifications for type promotion
- From the same table, type demotion, the reverse of type promotion is from lowest to highest. Type
demotion will result inaccurate value such as truncated value. Program examples for this section are
presented in formatted file input/output Module.
- This issue is very important aspect to be taken care when developing program that use mathematical
expressions as well as when passing argument values to functions.
- C++ has some more advanced features for typecasting and will be discussed in Typecasting Module.
Modifier Description
l (letter ell) Indicates that the argument is a long or unsigned long.
L Indicates that the argument is a long double.
Indicates that the corresponding argument is to be printed as a short or
h
unsigned short.
- The following table is a list of the ANSI C formatted output conversion of the printf() function,
used with %. The program examples are presented in Module 5.
www.tenouk.com Page 8 of 29
Characters from the string are printed until ‘\0’ is reached or
s char * until the number of characters indicated by the precision has
been printed.
u int Unsigned decimal notation.
Unsigned hexadecimal notation (without a leading 0x or 0X),
x, X int
use abcd for 0x or ABCD for 0X.
% - No argument is converted; just print a %.
- The following table is a list of ANSI C formatted input conversion of the scanf() function.
Example #1
www.tenouk.com Page 9 of 29
int a = 3000; //positive integer data type
float b = 4.5345; //float data type
char c = 'A'; //char data type
long d = 31456; //long positive integer data type
long e = -31456; //long -ve integer data type
int f = -145; //-ve integer data type
short g = 120; //short +ve integer data type
short h = -120; //short -ve integer data type
double i = 5.1234567890; //double float data type
float j = -3.24; //float data type
Output:
Example #2
www.tenouk.com Page 10 of 29
cout<<"\n2. \"short\" int sample: \t"<<q;
cout<<"\n3. \"unsigned short int\" sample: "<<r;
cout<<"\n4. \"float\" sample: \t\t"<<s;
cout<<"\n5. \"char\" sample: \t\t"<<t;
cout<<"\n6. \"long\" sample: \t\t"<<u;
cout<<"\n7. \"unsigned long\" sample: \t"<<v;
cout<<"\n8. negative \"long\" sample: \t"<<w;
cout<<"\n9. negative \"int\" sample: \t"<<x;
cout<<"\n10. negative \"short\" sample: \t"<<y;
cout<<"\n11. unsigned \"short\" sample: \t"<<z;
cout<<"\n12. \"double\" sample: \t\t"<<a;
cout<<"\n13. negative \"float\" sample: \t"<<b<<endl;
system("pause");
}
Output:
Example#3
int main( )
{
float area, circumference, radius;
Output:
www.tenouk.com Page 11 of 29
Example #4
int main()
{
cout<<"Hello there.\n";
cout<<"Here is 7: "<<7<<"\n";
//other than escape sequence \n used for new line, endl...
cout<<"\nThe manipulator endl writes a new line to the screen.\n"<<endl;
cout<<"Here is a very big number:\t" << 10000 << endl;
cout<<"Here is the sum of 10 and 5:\t" << (10+5) << endl;
cout<<"Here's a fraction number:\t" << (float) 7/12 << endl;
//simple type casting, from int to float
cout<<"And a very very big number:\t" << (double) 7000 * 7000<< endl;
//another type casting, from int to double
cout<<"\nDon't forget to replace existing words with yours...\n";
cout<<"I want to be a programmer!\n";
system("pause");
return 0;
}
Output:
Example #5
int main()
{
/* this is a comment
and it extends until the closing
star-slash comment mark */
cout<<"Hello World! How are you?\n";
//this comment ends at the end of the line
//so, new comment line need new double forward slash
cout<<"That is the comment in C/C++ program!\n";
cout<<"They are ignored by compiler!\n";
//double slash comments can be alone on a line
/* so can slash-star comments */
/********************************/
system("pause");
return 0;
www.tenouk.com Page 12 of 29
}
Output:
Example #6
int main()
{
cout<<"The size of an int is:\t\t"<<sizeof(int)<<" bytes.\n";
cout<<"The size of a short int is:\t"<<sizeof(short)<<" bytes.\n";
cout<<"The size of a long int is:\t"<<sizeof(long)<<" bytes.\n";
cout<<"The size of a char is:\t\t"<<sizeof(char)<<" bytes.\n";
cout<<"The size of a float is:\t\t"<<sizeof(float)<<" bytes.\n";
cout<<"The size of a double is:\t"<<sizeof(double)<<" bytes.\n";
cout<<"The size of a bool is:\t\t"<<sizeof(bool)<<" bytes.\n";
system("pause");
return 0;
}
Output:
Example #7
int main()
{
unsigned short int Width = 7, Length;
Length = 10;
cout<<"Width:\t"<<Width<<"\n";
cout<<"Length: "<<Length<<endl;
cout<<"Area: \t"<<Area<<endl;
system("pause");
return 0;
}
Output:
www.tenouk.com Page 13 of 29
Example #8
int main( )
{
int n;
int total, rate= 20;
Output:
Example #9
int main()
{
cout<<"For integer number from 32 till 127,\n";
cout<<"their representation for\n";
cout<<"characters is shown below\n\n";
cout<<"integer character\n";
cout<<"-------------------\n";
for (int i = 32; i<128; i++)
//display up to 127...
cout<<i<<" "<<(char) i<<"\n";
//simple typecasting, from int to char
system("pause");
return 0;
}
Output:
www.tenouk.com Page 14 of 29
- Boolean, bool is a lateral true or false. Use bool and the literals false and true to make Boolean logic
tests.
- The bool keyword represents a type that can take only the value false or true. The keywords false and
true are Boolean literals with predefined values. false is numerically zero and true is numerically one.
These Boolean literals are rvalues (right value); you cannot make an assignment to them.
- Program example:
int main()
{
bool val = false; // Boolean variable
int i = 1; // i is neither Boolean-true nor Boolean-false
int g = 5;
float j = 3.02; // j is neither Boolean-true nor Boolean-false
//Tests on integers
if(i == true)
cout<<"True: value i is 1"<<endl;
if(i == false)
cout<<"False: value i is 0"<<endl;
if(g)
cout << "g is true."<<endl;
else
cout << "g is false."<<endl;
www.tenouk.com Page 15 of 29
val = func();
if(val == false)
cout<<"func() returned false."<<endl;
if(val == true)
cout<<"func() returned true."<<endl;
system("pause");
return false;
//false is converted to 0
}
Output:
Example #10
int main()
{
Output:
www.tenouk.com Page 16 of 29
Example #11
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
printf("Conversion...\n");
printf("Start with any character and\n");
printf("Press Enter, EOF to stop\n");
num = getchar();
printf("Character Integer Hexadecimal Octal\n");
while(getchar() != EOF)
{
printf(" %c %d %x %o\n",num,num,num,num);
++num;
}
system("pause");
return 0;
}
Output:
Example #12
#include <stdio.h>
#include <stdlib.h>
www.tenouk.com Page 17 of 29
void dectobin();
int main()
{
char chs = 'Y';
do
{
dectobin();
printf("Again? Y, others to exit: ");
chs = getchar();
scanf("%c", &chs);
}while ((chs == 'Y') || (chs == 'y'));
return 0;
}
void dectobin()
{
int input;
printf("Enter decimal number: ");
scanf("%d", &input);
if (input < 0)
printf("Enter unsigned decimal!\n");
Output:
Example #13
#include <stdio.h>
#include <stdlib.h>
/*for strlen*/
#include <string.h>
www.tenouk.com Page 18 of 29
/*convert bin to decimal*/
void bintodec()
{
char buffbin[100];
char *bin;
int i=0;
int dec = 0;
int bcount;
i=strlen(bin);
for (bcount=0; bcount<i; ++bcount)
/*if bin[bcount] is equal to 1, then 1 else 0 */
dec=dec*2+(bin[bcount]=='1'? 1:0);
printf("\n");
printf("The decimal value of %s is %d\n", bin, dec);
}
int main(void)
{
bintodec();
return 0;
}
Output:
Example #14
char choice1;
char choice2;
/* numtest, value to test with, and pass to functions*/
int numtest;
/* value to convert to binary, and call decnumtobin function*/
int bintest;
int flag;
flag = 0;
go = 'y';
www.tenouk.com Page 19 of 29
do
{
printf("Enter the base of ur input(d=dec, h=hex, o=octal): ");
scanf("%c", &choice1);
getchar();
printf("\n");
printf("The entered Number: ");
/*If decimal number*/
if ((choice1 == 'd') || (choice1 == 'D'))
{
scanf("%d", &numtest);
getchar();
}
/*If hexadecimal number*/
else if ((choice1 == 'h') || (choice1 == 'H'))
{
scanf("%x", &numtest);
getchar();
}
/*If octal number*/
else if ((choice1 == 'o') || (choice1 == 'O'))
{
scanf("%o", &numtest);
getchar();
}
/*If no match*/
else
{
flag = 1;
printf("Only d, h or o options!\n");
printf("Program exit...\n");
exit(0);
}
printf("\n\nAn OPTION\n");
printf("=========\n");
printf("Do you wish to do the binary to decimal conversion?");
printf("\n Y for Yes, and N for no : ");
scanf("%c", &binY);
getchar();
/*If Yes...*/
if ((binY == 'Y') || (binY == 'y'))
/*Do the binary to decimal conversion*/
bintodec();
/*If not, just exit*/
else if ((binY != 'y') || (binY != 'Y'))
{
flag = 1;
printf("\nProgram exit...\n");
exit(0);
}
www.tenouk.com Page 20 of 29
printf("\n\n");
printf("The program is ready to exit...\n");
printf("Start again? (Y for Yes) : ");
scanf("%c", &go);
getchar();
/*initialize to NULL*/
numtest = '\0';
choice1 = '\0';
choice2 = '\0';
}
while ((go == 'y') || (go == 'Y'));
printf("-----FINISH-----\n");
return 0;
}
/*===================================================*/
void decimal(char *deci, int *decires)
{
int ans = *decires;
char ch = *deci;
if ((ch == 'd') || (ch == 'D'))
printf("\nThe number \"%d\" in decimal is equivalent to \"%d\" in
decimal.\n", ans, ans);
else if ((ch == 'h') || (ch == 'H'))
printf("\nThe number \"%X\" in hex is equivalent to \"%d\" in
decimal.\n", ans, ans);
else if ((ch == 'o') || (ch == 'O'))
printf("\nThe number \"%o\" in octal is equivalent to \"%d\" in
decimal.\n", ans, ans);
}
/*======================================================*/
void hexadecimal(char *hexa, int *hexares)
{
int ans = *hexares;
char ch = *hexa;
if ((ch == 'd') || (ch == 'D'))
printf("\nThe number \"%d\" in decimal is equivalent to \"%X\" in
hexadecimal.\n", ans, ans);
else if ((ch == 'h') || (ch == 'H'))
printf("\nThe number \"%X\" in hex is equivalent to \"%X\" in
hexadecimal.\n", ans, ans);
else if ((ch == 'o') || (ch == 'O'))
printf("\nThe number \"%o\" in octal is equivalent to \"%X\" in
hexadecimal.\n", ans, ans);
}
/*========================================================*/
void octal(char *octa, int *octares)
{
int ans = *octares;
char ch = *octa;
if ((ch == 'd') || (ch == 'D'))
printf ("\nThe number \"%d\" in decimal is equivalent to \"%o\" in
octal.\n", ans, ans);
else if ((ch == 'h') || (ch == 'H'))
printf("\nThe number \"%X\" in hex is equivalent to \"%o\" in
octal. \n", ans, ans);
else if ((ch == 'o') || (ch == 'O'))
printf("\nThe number \"%o\" in octal is equivalent to \"%o\" in
octal.\n", ans, ans);
}
void bintodec(void)
{
char buffbin[1024];
char *binary;
int i=0;
int dec = 0;
int z;
printf("Please enter the binary digits, 0 or 1.\n");
printf("Your binary digits: ");
binary = gets(buffbin);
i=strlen(binary);
for(z=0; z<i; ++z)
/*if Binary[z] is equal to 1, then 1 else 0 */
dec=dec*2+(binary[z]=='1'? 1:0);
printf("\n");
www.tenouk.com Page 21 of 29
printf("The decimal value of %s is %d", binary, dec);
printf("\n");
}
Output:
Example #15
www.tenouk.com Page 22 of 29
{
/* Yes or No value to continue with program */
char go;
char choice1;
char choice2;
/*numtest, value to test with, and pass to functions*/
int numtest;
/*value to convert to binary, and call decnumtobin function*/
int bintest;
int flag;
flag = 0;
go = 'y';
do
{
printf ("Enter the h for hex input: ");
scanf("%c", &choice1);
getchar();
printf ("\n");
printf ("Enter your hex number lor!: ");
printf ("\n\n");
printf ("The program is ready to exit...\n");
printf ("Start again? (Y for Yes) : ");
scanf ("%c", &go);
getchar();
/*initialize to NULL*/
numtest = '\0';
choice1 = '\0';
choice2 = '\0';
}
while ((go == 'y') || (go == 'Y'));
printf ("-----FINISH-----\n");
return 0;
}
/*===================================================*/
void decimal(char *deci, int *decires)
{
int ans = *decires;
char ch = *deci;
www.tenouk.com Page 23 of 29
printf ("\nThe number \"%X\" in hex is equivalent to \"%d\" in
decimal.\n", ans, ans);
}
Output:
Example #16
int main()
{
/*Program continuation...*/
char go;
www.tenouk.com Page 24 of 29
go = 'y';
do
{
printf("Playing with hex and ASCII\n");
printf("==========================\n");
printf("For hex, 0(0) - 1F(32) are non printable/control
characters!\n");
printf("For hex > 7F(127) they are extended ASCII characters that
are\n");
printf("platform dependent!\n\n");
printf("Enter the hex input: ");
scanf("%x", &numtest);
getchar();
decimal (&numtest);
printf("\nStart again? (Y for Yes) : ");
scanf ("%c", &go);
getchar();
/*initialize to NULL*/
numtest = '\0';
}
while ((go == 'y') || (go == 'Y'));
printf("-----FINISH-----\n");
return 0;
}
/*===================================================*/
void decimal(int *decires)
{
int ans = *decires;
/*If < decimal 32...*/
if(ans < 32)
{
printf("hex < 20(32) equivalent to non printable/control ascii
characters\n");
switch(ans)
{
case 0:{printf("hex 0 is NULL ascii");}break;
case 1:{printf("hex 1 is SOH-start of heading ascii");}break;
case 2:{printf("hex 2 is STX-start of text ascii");}break;
case 3:{printf("hex 3 is ETX-end of text ascii");}break;
case 4:{printf("hex 4 is EOT-end of transmission ascii");}break;
case 5:{printf("hex 5 is ENQ-enquiry ascii");}break;
case 6:{printf("hex 6 is ACK-acknowledge ascii");}break;
case 7:{printf("hex 7 is BEL-bell ascii");}break;
case 8:{printf("hex 8 is BS-backspace ascii");}break;
case 9:{printf("hex 9 is TAB-horizontal tab ascii");}break;
case 10:{printf("hex A is LF-NL line feed, new line ascii");}break;
case 11:{printf("hex B is VT-vertical tab ascii");}break;
case 12:{printf("hex C is FF-NP form feed, new page ascii");}break;
case 13:{printf("hex D is CR-carriage return ascii");}break;
case 14:{printf("hex E is SO-shift out ascii");}break;
case 15:{printf("hex F is SI-shift in ascii");}break;
case 16:{printf("hex 10 is DLE-data link escape ascii");}break;
case 17:{printf("hex 11 is DC1-device control 1 ascii");}break;
case 18:{printf("hex 12 is DC2-device control 2 ascii");}break;
case 19:{printf("hex 13 is DC3-device control 3 ascii");}break;
case 20:{printf("hex 14 is DC4-device control 4 ascii");}break;
case 21:{printf("hex 15 is NAK-negative acknowledge ascii");}break;
case 22:{printf("hex 16 is SYN-synchronous idle ascii");}break;
case 23:{printf("hex 17 is ETB-end of trans. block ascii");}break;
case 24:{printf("hex 18 is CAN-cancel ascii");}break;
case 25:{printf("hex 19 is EM-end of medium ascii");}break;
case 26:{printf("hex 1A is SUB-substitute ascii");}break;
case 27:{printf("hex 1B is ESC-escape ascii");}break;
case 28:{printf("hex 1C is FS-file separator ascii");}break;
case 29:{printf("hex 1D is GS-group separator ascii");}break;
case 30:{printf("hex 1E is RS-record separator ascii");}break;
case 31:{printf("hex 1F is US-unit separator ascii");}break;
}
}
else
printf ("\nThe number \"%X\" in hex is equivalent to \"%c\" ascii
character.\n", ans, ans);
}
www.tenouk.com Page 25 of 29
void decnumtobin (int *dec)
{
int input = *dec;
int i;
int count = 0;
int binary[128];
do
{
/* Modulus 2 to get 1 or a 0*/
i = input%2;
/* Load Elements into the Binary Array */
binary[count] = i;
/* Divide input by 2 for binary decrement */
input = input/2;
/* Count the binary digits*/
count++;
}while (input > 0);
Output:
Example #17
int main()
{
int num;
printf("Conversion...\n");
printf("Start with any character and\n");
printf("Press Enter, EOF to stop\n");
num = getchar();
www.tenouk.com Page 26 of 29
printf("Character Integer Hexadecimal Octal\n");
while(getchar() != EOF)
{
printf(" %c %d %x %o\n", num, num, num, num);
++num;
}
return 0;
}
Output:
/*main function*/
int main()
{
int p = 2000; /*positive integer data type*/
short int q = -120; /*variation*/
unsigned short int r = 121; /*variation*/
float s = 21.566578; /*float data type*/
char t = 'r'; /*char data type*/
long u = 5678; /*long positive integer data type*/
unsigned long v = 5678; /*variation*/
long w = -5678; /*-ve long integer data type*/
int x = -171; /*-ve integer data type*/
short y = -71; /*short -ve integer data type*/
unsigned short z = 99; /*variation*/
double a = 88.12345; /*double float data type*/
float b = -3.245823; /*float data type*/
www.tenouk.com Page 27 of 29
[bodo@bakawali ~]$ gcc datatype.c -o datatype
[bodo@bakawali ~]$ ./datatype
#include <stdio.h>
#include <stdlib.h>
int main()
{
char chs = 'Y';
do
{
dectobin();
printf("Again? Y, others to exit: ");
chs = getchar();
scanf("%c", &chs);
}while ((chs == 'Y') || (chs == 'y'));
return 0;
}
void dectobin()
{
int input;
printf("Enter decimal number: ");
scanf("%d", &input);
if (input < 0)
printf("Enter unsigned decimal!\n");
www.tenouk.com Page 28 of 29
[bodo@bakawali ~]$ gcc binary.c -o binary
[bodo@bakawali ~]$ ./binary
----------------------------------------------------o0o---------------------------------------------------
1. The ASCII, EBCDIC and UNICODE character sets reference Table can be found here: Character sets
Table.
2. Check the best selling C / C++ books at Amazon.com.
www.tenouk.com Page 29 of 29