2 Topic Two - Data Types (1)
2 Topic Two - Data Types (1)
1
• In this topic we shall see the essential computer
memory concepts, as well as how to get information
from users and store it as data using C language
data types
• We shall cover the following subtopics
– Memory concepts
– Data types
– Initializing variables and the assignment operator
– Printing variable contents
– Constants
– Programming conventions and styles
– scanf()
– Arithmetic in C
2
– Operator precedence
Memory concepts
4
Variable Attribute Description
Name The name of the variable used to reference
data in program code
Type The data type of the variable (number,
character, and so on)
Value The data value assigned to the memory location
Address The address assigned to a variable, which
points to a memory cell location
5
Example showing common variable attributes and sample
values.
6
Data types
• Data types refer to an extensive system used
for declaring variables or functions of different
types. The type of a variable determines how
much space it occupies in storage.
• In programming data types include; numbers,
dates, strings, Boolean, arrays, objects, and
data structures.
• The basic data types we shall concentrate on
are; char, int, float and double
7
Integers
• Integers are whole numbers that represent positive and
negative numbers, such as -3, -2, -1, 0, 1, 2, and 3, but not
decimal or fractional numbers.
• Integer data types hold a maximum of four bytes of
information and are declared with the int (short for integer)
keyword, as shown in the following line of code.
int x;
• In C, you can declare more than one variable on the same line
using a single int declaration statement with each variable
name separated by commas, as demonstrated next.
int x, y, z;
• The preceding variable declaration declares three integer
variables named x, y, and z.
• Remember that executable program statements such as a
print statement or in this case a variable declaration require a 8
Floating-Point Numbers
• Floating-point numbers are all numbers, including
signed and unsigned decimal and fractional
numbers. Signed numbers include positive and
negative numbers whereas unsigned numbers can
only include positive values. Examples of floating-
point numbers are shown in the following list.
⁻ 09.4543
⁻ 3428.27
⁻ 112.34329
⁻ -342.66
⁻ -55433.33281
• Single-precision floating-point (accurate up to 8
digits) 9
• We use the keyword float to declare floating-
point numbers, as shown next.
float operand1;
float operand2;
float result;
• The preceding code declares three floating-
point variable data types called operand1,
operand2, and result.
10
DOUBLE
•These are floating point numbers, both positive and
negative, which have a higher precision than float variables.
•Double variables are declared by using the double
keyword. Double comes from the term double precision,
which means that the numbers are twice as accurate as
floats, which are also known as single-precision numbers.
•Double-precision floating-point (accurate up to 16 digits)
•The keyword used to define double variables is
double
•An example of declaring a double variable called voltage is
double voltage;
Precision
• Precision deals with how accurately decimal numbers,
fractions, and very small and huge numbers are stored in
a computer
• For example if this value 123.4567891234 is defined as
float variable in C, the computer can store it only as a
single-precision value. It can accurately hold only the first
eight digits. The rest can be incorrect like this
123.456787.
• Here we can see that the first eight digits are correct but
after the eighth digit the value is wrong.
• For this case we can use double instead of float as double
precision can be accurate up to 16 decimal places
12
Characters
• Character data types are representations of integer values
known as character codes. For example, the character code
90 represents the letter Z. Note that the letter Z is not the
same as the character code 122, which represents the letter
z (lowercase letter z).
• Characters represent more than just the letters of the
alphabet; they also represent numbers 0 through 9, special
characters such as the asterisk (*), and keyboard keys such
as the Del (delete) key and Esc (escape) key. In all, there are
a total of 128 common character codes (0 through 127),
which make up the most commonly used characters of a
keyboard.
13
• Character variables are created using the char (short for
character) keyword as demonstrated below.
char firstInitial;
char middleInitial;
char lastInitial;
• Character data assigned to character variables must be
enclosed in single quotes ('), also known as tick marks or
apostrophes. As we shall see in the next section, the
equal sign (=) is used for assigning data to the character
variable
• C is a case sensitive programming language. So names
are case sensitive firstInitial is different from FIRSTINITIAL
as middleInitial is to Middleinitial.
14
Initializing Variables And The Assignment Operator
• When variables are first declared, the program assigns the
variable name (address pointer) to an available memory
location. It is never safe to assume that the newly
assigned variable location is empty. It’s possible that the
memory location contains previously used data (or
garbage). To prevent unwanted data from appearing in
your newly created variables, initialize the new variables,
as shown below.
/* Declare variables */
int x;
char firstInitial;
/* Initialize variables */
x = 0;
firstInitial = '\0';
15
• In the first part two variables : one integer and one
character data type are declared. After being created the
two variables are initialized to a particular value. The
integer variable is assigned the value zero (0), and the
character data type the character set \0, which is known as
the NULL character.
• Notice that single quotes are required when assigning data
to the character data type.
• When assigning data to variables such as variable
initialization, the equal sign is not used in a comparative
sense. In other words, you would not say that x equals 0.
Rather, programmers say variable x is taking on the value of
0.
• Remember, when assigning data to variables, such as
initializing, you refer to the equal sign as an assignment
operator, not a comparison operator. 16
• We can also initialize variables while declaring
them, as shown below.
int x = 0;
char firstInitial = '\0’;
• The code above accomplishes the same tasks
in two lines as what the following code
accomplishes in four.
int x;
char firstInitial;
x = 0;
firstInitial = '\0';
17
• We are required to announce variables to the
C compiler before we use them. We announce
them by providing a list of variables near the
top of the source code. That way, the compiler
knows what the variables are called; the types
of those variables and the amount of storage
required for those variables. Officially, this
process is known as declaring your variables.
18
Printing Variable Contents
• To print the contents of variables, we use the printf() function with a few new
formatting options, as demonstrated in the following code block.
#include <stdio.h>
main()
{
/*variable declarations*/
int x;
float y;
char c;
/*variable initializations*/
x = -4443;
y = 554.21;
c = 'M';
/*printing variable contents to standard output*/
printf("\nThe value of integer variable x is %d", x);
printf("\nThe value of float variable y is %f", y);
printf("\nThe value of character variable c is %c\n", c);
return 0;
} 19
#include <stdio.h>
main()
{
/*variable declarations*/
int x;
float y;
char c;
/*variable initializations*/
x = -4443;
y = 554.21;
c = 'M';
/*printing variable contents to standard output*/
printf("\nThe value of integer variable x is %d", x);
printf("\nThe value of float variable y is %f", y);
printf("\nThe value of character variable c is %c\n", c);
return 0;
} 20
• First, we declare three variables (one integer,
one float, and one character), and then we
initialize each of them. After initializing the
variables, we use the printf() function and
conversion specifiers to output each variable’s
contents to the computer screen.
21
Conversion Specifiers
• Because information is stored as unreadable data in
the computer’s memory, programmers in C must
specifically tell input or output functions, such as
printf(), how to display the data as information.
• We can accomplish this seemingly difficult task using
character sets known as conversion specifiers.
• Conversion specifiers are used to display unreadable
data in a computer’s memory as information.
• Conversion specifiers are comprised of two
characters: The first character is the percent sign (%),
and the second is a special character that tells the
program how to convert the data.
22
Common conversion specifiers(placeholders)
Conversion Specifier Description
%d Displays integer value
%f Displays float or double numbers
%c Displays a single character
%i Displays integer value
%ld long int (same as %li)
%lf Double
%s String
%x Hexadecimal
%e Float or double exponential format
%g Float or double use %f or %e as required
%o int unsigned octal value
%p pointer address stored in pointer
%s array of char sequence of characters(string) 23
Displaying Integer Data Types with printf()
24
• The %d conversion specifier can also be used to output
the contents of a variable declared as integer data type,
as shown below.
int a;
a= 29;
printf("The value of a is %d", a);
• In the statements above a new integer a is declared,
after that number 29 is assigned to the newly created
variable and its contents are displayed using printf()
function with the %d conversion specifier
• Each variable displayed using a printf() function must be
outside the parentheses and separated with a comma (,).
25
Displaying Floating-Point Data Types with printf()
• To display floating-point numbers, use the %f
conversion specifier demonstrated below.
printf("%f", 55.55);
• Here’s another example of the %f conversion
specifier, which prints the contents of a
floating-point variable:
float result;
result = 3.123456;
printf("The value of result is %f", result);
26
• Although the %f conversion specifier displays
floating-point numbers, it may not be enough to
display the floating-point number with correct or
wanted precision.
• The following printf() function demonstrates the
precision problem.
printf("%f", 55.55);
• This printf() example outputs a floating-point
number with a six-digit precision to the right of the
decimal point, as shown below.
55.550000
27
• To create precision with floating-point numbers, adjust the
conversion specifier using numbering schemes between the %
sign and the f character conversion specifier.
printf("%.1f", 3.123456);
printf("\n%.2f", 3.123456);
printf("\n%.3f", 3.123456);
printf("\n%.4f", 3.123456);
printf("\n%.5f", 3.123456);
printf("\n%.6f", 3.123456);
• The preceding code block produces the following output:
3.1
3.12
3.123
3.1234
3.12345
3.123456
• Notice without the new line (\n) escape sequence, each
statement’s output would be generated on the same line,
making it difficult to read. 28
#include<stdio.h>
main(){
printf("%.1f", 3.123456);
printf("\n%.2f", 3.123456);
printf("\n%.3f", 3.123456);
printf("\n%.4f", 3.123456);
printf("\n%.5f", 3.123456);
printf("\n%.6f", 3.123456);
return 0;
}
29
Displaying Character Data Types with printf()
• Characters are also easy to display using the %c
conversion specifier.
printf("%c", 'M');
• The output of this statement is simply the
single letter M.
• Like the other conversion specifiers, you can
output the contents of a character variable data
type using the %c conversion specifier and a
printf() function as demonstrated next.
char firstInitial;
firstInitial = 'S';
printf("The value of firstInitial is %c", firstInitial); 30
• You can use multiple conversion specifiers in a
single printf() function:
char firstInitial, middleInitial, lastInitial;
firstInitial = 'M';
middleInitial = 'A';
lastInitial = 'V';
printf("My Initials are %c.%c.%c.", firstInitial, middleInitial,
lastInitial);
• The output of the preceding program statements is
My Initials are M.A.V.
31
#include<stdio.h>
main(){
char firstinitial, middleinitial, lastinitial;
firstinitial = 'm';
middleinitial = 'a';
lastinitial = 'v';
printf("my initials are %c.%c.%c.",
firstinitial, middleinitial, lastinitial);
return 0;
}
32
• Notice in the statement below that each
variable displayed with the printf() function is
outside the double quotes and separated with
a single comma.
printf("My Initials are %c.%c.%c.", firstInitial,
middleInitial, lastInitial);
• Text inside of printf()’s double quotes is
reserved for displayable text, conversion
specifiers, and escape sequences.
33
CONSTANTS
• Often referred to as read-only variables, constant
data types cannot lose their data values during
program execution. They are most commonly used
when you need to reuse a common data value
without changing it.
• Constant data values can be of many data types but
must be assigned when the constant is first created,
as demonstrated next.
const int x = 20;
const float PI = 3.14;
34
• Notice that the keyword const precedes the data-
type name, signaling that this is a read-only variable
or constant. You can print the values of constants in
the same way that normal variables are printed using
conversion specifiers with the printf() function as
shown in the following program code:
#include <stdio.h>
main()
{
const int x = 20;
const float PI = 3.14;
printf("\nConstant values are %d and %.2f\n", x, PI);
}
• The program will display Constant values are 20 and
3.14
35
#include <stdio.h>
main()
{
const int x = 20;
const float PI = 3.14;
printf("\nConstant values are %d
and %.2f\n", x, PI);
}
36
Rules to follow when naming variables
• Always begin your variable names with a
lowercase letter.
• Do not use spaces in your variable names.
• Only use letters, numbers, and underscores (_)
in your variable name
• Keep variable names fewer than 31 characters
37
Scanf()
• The scanf() function is another built in function
provided by the standard input output library
<stdio.h>; it reads standard input from the
keyboard and stores it in previously declared
variables. It takes two arguments as
demonstrated next.
scanf("conversion specifier", variable);
• The conversion specifier argument tells scanf()
how to convert the incoming data. We use the
same conversion specifiers as discussed before.
38
Common conversion specifiers used with scanf ()
39
• The following code represents a complete C program
which uses the scanf() function to read in two integers
and add them together.
#include <stdio.h>
main()
{
int a= 0;
int b= 0;
printf("\nEnter first integer: ");
scanf("%d", &a);
printf("Enter second integer: ");
scanf("%d", &b);
printf("The result is %d\n", a+ b);
} 40
• The first notable line of code prompts the user to enter a
number.
printf("\nEnter first operand: ");
• The printf function above does not contain a variable at the
end, nor does it include the escape sequence \n at the end of
the statement. By leaving the new line escape sequence off
the end of a print statement, program control pauses while
waiting for user input.
• The next line of code uses the scanf() function to receive input
from the user.
scanf("%d", &a);
• The first scanf() argument takes the integer conversion
specifier ("%d"), which tells the program to convert the
incoming value to an integer.
41
• The second operator is an address operator
(&), followed by the name of the variable.
Essentially, the address operator contains a
pointer to the location in memory where your
variable is located.
• Forgetting to place the address operator (&) in
front of your variable in a scanf() function will
cause problems with memory access during
program execution.
42
• After receiving both numbers from the user, a
print statement is used to display the
following result.
printf("The result is %d\n", a+ b);
• In this print statement, a single conversion
specifier (%d) tells the program to display a
single integer value. In the next argument of
the printf() function, both numbers input by
the user are added using the addition sign (+).
43
Common Arithmetic Operators
Operator Description
* Multiplication
/ Division
% Modulus (remainder)
+ Addition
− Subtraction
44
Arithmetic In C
• As demonstrated in the program from the
previous section, C enables programmers to
perform all types of arithmetic.
• Table below demonstrates the most common
arithmetic operators used in beginning C
programming.
• In the program from the previous section we
performed the calculation in the printf()
function. Although this is not required, you
can use additional variables and program
statements to derive the same outcome.
45
• For example, the following code is another
variation of the program that uses additional
program statements to achieve the same result.
#include <stdio.h>
main()
{
int a= 0;
int b= 0;
int c= 0;
printf("\nEnter first number: ");
scanf("%d", &a);
printf("Enter second number: ");
scanf("%d", &b);
c= a+ b;
printf("The result is %d\n", c);
} 46
• In this program, we used two additional
statements to derive the same outcome.
• Instead of performing the arithmetic in the
printf() function, we have declared an
additional variable called c and assigned to it
the result of a+ b using a separate statement,
as demonstrated next.
c = a + b;
47
• It is important to remember that the equal
sign (=) is an assignment operator, where the
right side is being assigned to the left side of
the operator (=).
• For example, you would not say the following:
c equals a plus b.
• That is incorrectly stated. Instead you would
say:
c gets the value of a plus b.
48
Operator Precedence
• Operator precedence is very important when
dealing with arithmetic in any programming
language. Operator precedence in C is shown in
table below.
• Order or Precedence Description
() Parentheses are
evaluated first, from
innermost to outermost
*, /, % Evaluated second, from
left to right
+, − Evaluated last, from left to
right
49
• Take the following formula, for example, which uses
parentheses to dictate the proper order of operations.
f = (a – b)(x – y);
• Given a = 5, b = 1, x = 10, and y = 5, you could
implement the formula in C using the following syntax.
f= (5 – 1) * (10 – 5);
• Using the correct order of operations, the value of f
would be 20. Take another look at the same
implementation in C this time without using
parentheses to dictate the correct order of operations.
f = 5 1 * 10 5;
• Neglecting to implement the correct order of
operations, f would result in 10.
50
• C code needed to create the Profit program
#include <stdio.h>
main()
{
float revenue, cost;
revenue = 0;
cost = 0;
/* profit = revenue - cost */
printf("\nEnter total revenue: ");
scanf("%f", &revenue);
printf("\nEnter total cost: ");
scanf("%f", &cost);
printf("\nYour profit is $%.2f\n", revenue - cost);
} 51