Module2 PDF
Module2 PDF
PROGRAM STRUCTURE
AND BASIC DATA TYPES
My Training Period: hours
Note: ANSI C refers to ISO/IEC C.
Abilities
2.1
A Program
2.2
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 cant use these
words for identifiers such as variable names.
The following table is a list of keywords used in ANSI C.
Keyword
auto
break
case
char
const
continue
default
do
double
elif
else
endif
enum
extern
float
for
goto
if
ifdef
ifndef
int
long
www.tenouk.com
Description
register
return
short
signed
sizeof
static
struct
switch
typedef
union
unsigned
void
volatile
while
Another storage class specifier. Used to advise the compiler to place the
variables in machines processor register instead of machines 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
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,
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
equivalent range for signed char is -128 and 127 (2s complement
machine).
An operator. Shows the number of bytes (occupied or) required to store an
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
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
various types.
Used in a selection program control. Used together with case label to test
whether an expression matches one of a member of cases constant integer
and branches accordingly.
Used to create new data type name.
A variable that may hold (at different time) objects of different types and
sizes. If at the same time, use struct.
A qualifier may be applied to char or any integer. For example, 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
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
otherwise occur.
Used for conditional loop execution. Normally together with the do.
Table 2.1: ANSI C Keywords
The following table is a list of C++ keywords; most of the keywords will be used in Tutorial #2 and #3.
Keywords
asm
catch
bool
class
const_cast
delete
dynamic_cast
explicit
www.tenouk.com
Brief descriptions
Page 2 of 29
false
2.3
One way to master C/C++ programming is to master the keywords and usages :o).
Identifiers
2.4
The first character of an identifier must be a letter, an underscore ( _ ) also counts as a letter.
The blank or white space character is not permitted in an identifier.
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.
Reserved words/keywords and characters such as main and # also cannot be used.
Variables
www.tenouk.com
Page 3 of 29
Initializing a variable means, give a value to the variable, that is the variables 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.
General form:
data_type variable_list;
Note the blank space.
m, n;
total, rate;
user_response;
color[7];
n = 20;
rate = 4.5;
user_response = n;
color = "green";
2.5
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 variables 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
integer
long
integer
short
integer
unsigned
integer
character
Keyword
Bits
16
int
long
32
-4294967296 to 4294967295
-128 to 127
16
0 to 65535
short
unsigned
char
floating
point
double
floating
point
32
float
Range
-32768 to 32767
64
double
0 to 255
approximately 6 digits of
precision
approximately 12 digits
of precision
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).
Type
Size (bits)
unsigned char
0 to 255
char
-128 to 127
enum
unsigned int
16
16
-32,768 to 32,767
0 to 65,535
short int
16
-32,768 to 32,767
int
16
-32,768 to 32,767
unsigned long
32
long
32
float
32
0 to 4,294,967,295
-2,147,483,648 to
2,147,483,647
3.4-1038 to 3.41038
double
64
Range
1.7
-10308
to 1.7
10308
-104932
long double
near pointer
80
16
3.4
to 1.1104932
Not applicable
far pointer
32
Not applicable
Sample applications
Small numbers and full PC
character set
Very small numbers and ASCII
characters
Ordered sets of values
Larger numbers and loops
Counting, small numbers, loop
control
Counting, small numbers, loop
control
Astronomical distances
Large numbers, populations
Scientific (7-digit precision)
Scientific (15-digit
precision)
Financial (18-digit precision)
Manipulating memory addresses
Manipulating addresses outside
current segment
Type
Size (bits)
Range
unsigned char
0 to 255
char
-128 to 127
short int
16
-32,768 to 32,767
unsigned int
32
int
32
unsigned long
32
enum
32
long
32
0 to 4,294,967,295
-2,147,483,648 to
2,147,483,647
0 to 4,294,967,295
-2,147,483,648 to
2,147,483,647
-2,147,483,648 to
2,147,483,647
float
32
3.4
-1038
double
64
1.7
-10308
long double
80
3.4
-104932
www.tenouk.com
to 1.71038
to 3.410308
to
Page 5 of 29
Sample applications
Small numbers and full PC
character set
Very small numbers and ASCII
characters
Counting, small numbers, loop
control
Large numbers and loops
Counting, small numbers, loop
control
Astronomical distances
Ordered sets of values
Large numbers, populations
Scientific (7-digit)
precision)
Scientific (15-digit
precision)
Financial (18-digit
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:
0
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:
0x
0x8
0XADC
The literal data-type qualifiers bring different means for same constant data. For example:
2.6
07
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.
Escape Sequence
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.
Code
\a
\t
\b
\\
\f
\
\n
\"
\r
\0
Code Meaning
Audible bell
Horizontal tab
Backspace
Backslash character
Formfeed
Single quote character
Newline
Double quote character
Carriage return
NULL, ASCII 0
Table 2.6: 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.
Sequence
\a
\b
\f
\n
\r
\t
\v
\\
\'
\"
\?
\o
\xH
www.tenouk.com
Value (hex)
0x07
0x08
0x0C
0x0A
0x0D
0x09
0x0B
0x5c
0x27
0x22
0x3F
Char
What it does
BEL
BS
FF
LF
CR
HT
VT
\
'
"
?
any
any
Audible bell
Backspace
Formfeed
Newline (linefeed)
Carriage return
Tab (horizontal)
Vertical tab
Backslash
Single quote (apostrophe)
Double quote
Question mark
o=a string of up to three octal digits
H=a string of hex digits
Page 6 of 29
\XH
any
Constants
2.8
int
day_in_week = 7;
float
total_loan = 1100000.35;
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:
'$'
'*'
' '
'z'
'P'
2.9
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:
int total, number;
float average;
But in the middle of your program you encountered the following expression:
average = total / number;
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
average =
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:
(type) such as (int), (float) and (char).
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(). Cs 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.
Data type
long double
double
float
unsigned long int
long int
unsigned int
int
short
char
printf conversion
specification
%Lf
%f
%f
%lu
%ld
%u
%d
%hd
%c
scanf conversion
specification
%Lf
%lf
%f
%lu
%ld
%u
%d
%hd
%c
Description
Indicates that the argument is a long or unsigned long.
Indicates that the argument is a long double.
Indicates that the corresponding argument is to be printed as a short or
unsigned short.
Table 2.9: Length modifier
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.
Character
Argument type
c
d, i
int
int
e, E
double
double
g, G
double
int *
o
p
int
void
www.tenouk.com
Converted to
char *
int
x, X
int
The following table is a list of ANSI C formatted input conversion of the scanf() function.
Character
Input Data
Characters.
Decimal integer.
Integer.
n
o
p
s
u
x
e, f, g
[]
[^]
%
Argument Type
Floating-point number.
Matches the longest nonempty string of input
characters from the set
between brackets.
Matches the longest nonempty string of input
characters not from the set
between brackets.
Literal %.
www.tenouk.com
//main( ) function
Page 9 of 29
int
float
char
long
long
int
short
short
double
float
a
b
c
d
e
=
=
=
=
=
f =
g =
h =
i =
j =
Output:
Example #2
//Another data type program example
#include <iostream.h>
#include <stdlib.h>
void main()
//main( ) function
{
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
cout<<"\t--Data type again--\n";
cout<<"\t-------------------\n";
cout<<"\n1.
\"int\" sample: \t\t"<<p;
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
//Program to calculate the circumference and area of circle
#include <iostream.h>
#include <stdlib.h>
//define identifier PI with constant
#define PI
3.14159
//define identifier TWO with constant
#define TWO 2.0
int main( )
{
float
area, circumference, radius;
cout<<"\nEnter the radius of the circle in meter: ";
cin>>radius;
area = PI * radius * radius;
//circle area = PI*radius*radius
circumference = TWO * PI * radius;
//circumference = 2*PI*radius
cout<<"\nCircumference = "<<circumference<<" meter";
//circle circumference
cout<<"\nCircle area = "<<area<<" square meter"<<endl;
//circle area
system("pause");
return 0;
}
Output:
www.tenouk.com
Page 11 of 29
Example #4
//Using cout from iostream.h header file
#include <iostream.h>
#include <stdlib.h>
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
//Comment in C/C++, using /* */ or //
//the // only for C++ compiler
#include <iostream.h>
#include <stdlib.h>
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
//By using predefined sizeof() function,
//displaying the data type size, 1 byte = 8 bits
#include <iostream.h>
#include <stdlib.h>
int main()
{
cout<<"The size of
cout<<"The size of
cout<<"The size of
cout<<"The size of
cout<<"The size of
cout<<"The size of
cout<<"The size of
system("pause");
return 0;
}
Output:
Example #7
//Demonstration the use of variables
#include <iostream.h>
#include <stdlib.h>
int main()
{
unsigned short int
Length = 10;
Width = 7, Length;
Output:
www.tenouk.com
Page 13 of 29
Example #8
//To calculate the total amount of money earned in n days
#include <iostream.h>
#include <stdlib.h>
int main( )
{
int n;
int total, rate= 20;
cout<<"Enter number of days worked: ";
cin>>n;
total = n * rate;
cout<<"\n----------------------------";
cout<<"\n|
For rate RM20 per day
|";
cout<<"\n----------------------------";
cout<<"\n";
cout<<"\nFor "<<n<<" days of work, you have earned $ ";
cout<<total<<endl;
system("pause");
return 0;
}
Output:
Example #9
//Printing characters base on their
//respective integer numbers
#include <iostream.h>
#include <stdlib.h>
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:
// Boolean variable
// i is neither Boolean-true nor Boolean-false
// j is neither Boolean-true nor Boolean-false
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
//Testing the escape sequences
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("Testing the escape sequences:\n");
printf("-----------------------------\n");
printf("The audible bell --->\'\\a\' \a\a\a\n");
printf("The backspace
--->\'\\b\' \bTesting\n");
printf("The formfeed, printer
--->\'\\f\' \fTest\n");
printf("The newline
--->\'\\n\' \n\n");
printf("The carriage return
--->\'\\r\' \rTesting\n");
printf("The horizontal tab
--->\'\\t\' \tTesting\t\n");
printf("The vertical tab --->\'\v\' \vTesting\n");
printf("The backslash
--->\'\\\\' \\Testing\\\n");
printf("The single quote --->\'\'\' \'Testing\'\'\'\n");
printf("The double quote --->\'\"\' \"Testing\"\"\n");
printf("The question mark --->\'\?\' \?Testing\?\n");
printf("Some might not working isn't it?\n");
system("pause");
return 0;
}
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>
/*convert decimal to binary function*/
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");
/*for the mod result*/
int i;
/*count the binary digits*/
int count = 0;
/*storage*/
int binbuff[64];
do
{
/* Modulus 2 to get the remainder of 1 or 0*/
i = input%2;
/* store the element into the array */
binbuff[count] = i;
/* Divide the input by 2 for binary decrement*/
input = input/2;
/* Count the number of binary digit*/
count++;
/*repeat*/
}while (input > 0);
/*prints the binary digits*/
printf ("The binary representation is: ");
do
{
printf("%d", binbuff[count - 1]);
count--;
if(count == 8)
printf(" ");
} while (count > 0);
printf ("\n");
}
Output:
Example #13
#include <stdio.h>
#include <stdlib.h>
/*for strlen*/
#include <string.h>
www.tenouk.com
Page 18 of 29
Output:
Example #14
/*Playing with binary, decimal, hexadecimal
and octal conversion*/
#include <stdio.h>
#include <stdlib.h>
/*strlen*/
#include <string.h>
/*octal conversion function*/
void octal(char *octa, int *octares);
/*hexadecimal conversion function */
void hexadecimal(char *hexa, int *hexares);
/*decimal conversion function */
void decimal(char *deci, int *decires);
/*convert binary to decimal*/
void bintodec(void);
/* convert decimal to binary*/
void decnumtobin (int *dec);
int main()
{
/* Yes or No value to continue with program */
char go;
/* Yes or No value to proceed to Binary to Decimal function */
char binY;
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);
}
/*Firstly convert the input 'number' to binary*/
bintest = numtest;
decnumtobin(&bintest);
/*output the hex, decimal or octal*/
printf("\n");
printf("Next, enter the base of ur output (d=dec, h=hex, o=octal):
");
scanf("%c", &choice2);
getchar();
/*If decimal number*/
if ((choice2 == 'd') || (choice2 == 'D'))
decimal (&choice1, &numtest);
/*If hexadecimal number*/
else if ((choice2 == 'h') || (choice2 == 'H'))
hexadecimal (&choice1, &numtest);
/*If octal number*/
else if ((choice2 == 'o') || (choice2 == 'O'))
octal (&choice1, &numtest);
/*if nothing matched*/
else
{
flag = 1;
system("cls");
printf("Only d, h or o options!");
printf("\nProgram exit...");
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
Output:
Example #15
/*Playing with binary, decimal, hexadecimal
and octal conversion*/
#include <stdio.h>
#include <stdlib.h>
/*strlen*/
#include <string.h>
/*decimal conversion function */
void decimal(char *deci, int *decires);
/* convert decimal to binary*/
void decnumtobin (int *dec);
int main()
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!: ");
/*If hexadecimal number*/
if ((choice1 == 'h') || (choice1 == 'H'))
{
scanf ("%x", &numtest);
getchar();
}
else
{
flag = 1;
printf ("Only h!\n");
printf("Program exit...\n");
exit(0);
}
/*Firstly convert the input 'number' to binary*/
bintest = numtest;
decnumtobin(&bintest);
/*output the hex, decimal or octal*/
printf ("\n");
printf ("Enter the d for decimal output: ");
scanf ("%c", &choice2);
getchar();
/*If decimal number*/
if ((choice2 == 'd') || (choice2 == 'D'))
decimal(&choice1, &numtest);
/*else...*/
else
{
flag = 1;
printf("Only d!");
printf("\nProgram exit...");
exit(0);
}
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 == 'h') || (ch == 'H'))
www.tenouk.com
Page 23 of 29
Output:
Example #16
/*Playing with hexadecimal and ascii*/
#include <stdio.h>
#include <stdlib.h>
/*strlen*/
#include <string.h>
/*decimal conversion function */
void decimal(int *decires);
/*convert decimal to binary*/
void decnumtobin (int *dec);
int main()
{
/*Program continuation...*/
char go;
/* numtest, value to test with, and pass to functions*/
int numtest;
/* value to convert to binary, and call decnumtobin function*/
int bintest;
int flag = 0;
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();
/*Firstly convert the input 'number' to binary*/
bintest = numtest;
decnumtobin(&bintest);
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
Output:
Example #17
www.tenouk.com
Page 26 of 29
Output:
p
q
r
s
t
u
v
w
x
y
z
a
b
=
=
=
=
=
=
=
=
=
=
=
=
=
2000;
-120;
121;
21.566578;
'r';
5678;
5678;
-5678;
-171;
-71;
99;
88.12345;
-3.245823;
www.tenouk.com
Page 27 of 29
"int" sample:
2000, the data size: 4 bytes
"short" int sample:
-120, the data size: 2 bytes
"unsigned short int" sample: 121, the data size: 2 bytes
"float" sample:
21.5665779, the data size: 4 bytes
"char" sample:
r, the data size: 1 byte
"long" sample:
5678, the data size: 4 bytes
"unsigned long" sample:
5678, the data size: 4 bytes
negative "long" sample:
-5678, the data size: 4 bytes
negative "int" sample:
-171, the data size: 4 bytes
negative "short" sample:
-71, the data size: 2 bytes
unsigned "short" sample:
99, the data size: 2 bytes
"double" sample:
88.1235, the data size: 8 bytes
negative "float" sample:
-3.24582, the data size: 4 bytes
#include <stdio.h>
#include <stdlib.h>
/*convert decimal to binary function*/
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");
/*for the mod result*/
int i;
/*count the binary digits*/
int count = 0;
/*storage*/
int binbuff[64];
do
{
/* Modulus 2 to get the remainder of 1 or 0*/
i = input%2;
/* store the element into the array */
binbuff[count] = i;
/* Divide the input by 2 for binary decrement*/
input = input/2;
/* Count the number of binary digit*/
count++;
/*repeat*/
}while (input > 0);
/*prints the binary digits*/
printf("The binary representation is: ");
do
{
printf("%d", binbuff[count - 1]);
count--;
if(count == 8)
printf(" ");
} while (count > 0);
printf ("\n");
}
www.tenouk.com
Page 28 of 29
1.
2.
The ASCII, EBCDIC and UNICODE character sets reference Table can be found here: Character sets
Table.
Check the best selling C / C++ books at Amazon.com.
www.tenouk.com
Page 29 of 29