Components of A C Program (Part 3)
Components of A C Program (Part 3)
(Part 3)
1
Topics
• Type
• Variables
• Keywords and Identifiers
• Assignments
• Constant Variables
2
Type
• The kind of a value is its “type”
• Not all values are of the same kind
– For example: 7 + “cat” makes no sense
Variable
Value 3
Type
• Built-in types: char, int, float
• Type modifiers: long, short, const
• User-defined types (arrays and records)
• What about “strings”?
– Strings are arrays of char (discussed later)
4
Character Representation
• Characters are stored as a small integer
• Each character has a unique integer
equivalent specified by its position in the
ASCII table (pronounced “as-key”)
– American Standard Code for Information Interchange
5
6
Character Representation
• The ASCII values range from 0 to 127
– value 0: special character ’\0’
(a.k.a. NULL character)
– value 127: special character <DEL>
– other special characters:
’\n’ ’\t’ ’\’’ ’\\’ etc.
– various “extended” sets from 128 to 255
7
Variable
• Is a logical name for a container
– (an actual piece of computer memory for
values)
• Has a type associated with it
– tells the computer how to interpret the bits
• Must be declared before use:
int i; float result;
int i=0; char initial=’K’;
8
Variable Declaration: Examples
int myID;
myID
9
Variable Declaration: Examples
int myID;
10
Variable Declaration: Examples
int myID;
11
Variable Declaration: Examples
int myID;
12
Variable Declaration: Examples
float commission = 0.05;
17
Assignment
• Puts a specified value into a specified
variable
• Assignment operator: =
not to be
confused
with ==
18
Assignment: Examples
float x = 2.5 ;
char ch ;
int number ;
ch = ’\n’ ;
number = 4 + 5 ;
/* current value of number is 9. */
number = number * 2;
/* current value of number is now 18. */ 19
Assignment
• Value must have a type assignable to the
variable
• Value may be automatically converted to fit
the new container
• Example:
– various.c
20
#include <stdio.h>
integer = 33.33;
/* Do various assignment character = 33.33;
statements */
floatingPoint = 33.33;
int main()
{ integer = floatingPoint;
int integer; floatingPoint = integer;
char character;
float floatingPoint; return 0;
}
integer = 33;
character = 33;
floatingPoint = 33;
integer = 'A';
character = 'A';
floatingPoint = 'A'; 21
various.c
Constant Variables
• ...are variables that don’t vary
• ...may not be assigned to.
• ...must be initialized
22
Constant Variables: Examples
const int myID = 192;
24
Example: Constants
#include <stdio.h>
/* Converts an angle in degrees to
radians. */
“Global” const float PI = 3.1415926;
constant variable
int main()
{
float angleInDegs;
float angleInRads;
angleInRads = PI/180*angleInDegs;
printf("%f\n", angleInRads);
return 0;
}
more on this later... 25