Chapter 2 Data Types and Variables
1. VARIABLE AND BASEIC DATATYPES
As a programmer, you will frequently wantyour program to “remember” a value. For example, if your program requests avalue form the user, or if it calculates a value, you will want to remember itsomewhere so you can use it later. The way your program remembers things is byusing variables. For example:
Int b;
This line is to create a variable called bthat is able to hold one integer value.
A variable has a name(in this case, b) anda type(in this case, int , an integer)
You can store a value in b by sayingsomething like
b=5;
you can use the value in b by sayingsomething like
printf(“%d”, b);
#include <stdio.h>
int main() { int b; b = 5; printf("%d", b); return 0; } |
In c, there are several standard types forvariables:
Bool-true or false, typically stored in onebyte.
Int-integer(whole number) values
Float-floating point values
Char- single character value (such as “m”or “Z”)
There are also several variants on thesetypes such as double, unsigned int, long, unsigned long
Type size
Char,unsigned char, signed char 1 byte
Short, unsigned short 2 bytes
Int, unsigned int 4 bytes
Long, unsigned long 4 bytes
Float 4bytes
Double 8bytes
VariableNames
Every variable has a name and a value. Thename identifies the variable, the value stores data
Every variable name in C must start with aletter, the rest of the name can consist of the letters, numbers and underscorecharacters.
C recognizes upper and lower casecharacters as being different
Finally, you cannot use any of C’s keywordslike mani, while, switch ect as variable names.
Examples of legal variable names include
X result outfile bestyet
X1 x2 out_file best_yet
Power impetus gamman hi_score
Variableinitialization
At compile time in the declaration
e.g intx = 5;
charcode = ‘B’;
inti=0;
at run time by an assignment
e.gx=5
at run time by an input statement
e.g.scanf(“%d”, &x);
Constants
To define a constant define a “variable”(usually, U.C.) with keyword.
const
This is how it works:
Constfloat PI=3.1415926;
This does NOT work:
Constfloat PI=3.0;
PI= 3.1415926; /*not allowed to change it*/
#include <stdio.h>
int main() { const float PI = 3.14159; PI = 3.14; return 0; } |
Error: assignment of read-only variable ‘PI’ |
#include <stdio.h> int term; /* term used in two expression */ int main() { term = 3 * 5; printf("Twice %d is %d\n", term, 2 * term); printf("Three times %d is %d\n", term, 3 * term); return 0; } |
Floating Point Versus Integer Divide
The division operator is special, There isvast difference between an integer divide and floating-point an integer divide,the result is truncated (any fractional part is discarded). So the value of19/10 is 1
Expression result result type
1+2 3 integer
1.0+2.0 3.0 floating point
19/10 1 integer
19.0/10.0 1.0 floating point
C allows the assignme of an integerexpression to floating-point variable, C will automatically perform theconversion from integer to floating point, a similar conversion is performedwhen a floating-point number is assigned to an integer.
For example:
#include <stdio.h> int integer; /* an integer */ float floating; /* a floating-point number */ int main() { floating = 1.0 / 2.0; /* assign "floating" 0.5 */ printf("%f\n", floating); integer = 1 / 3; /* assign integer 0 */ printf("%d\n, integer"); integer = (1 / 2) + (1 / 2); /* assign floating 0 */ printf("%d\n, integer"); floating = 3.0 / 2.0; /* assign floating 1.5 */ printf("%f\n", floating); integer = floating; /* assign integer 1 */ printf("%d\n, integer"); return 0; } |
Why is an incorrect result printed?
#include <stdio.h> float result; /* result of the divide */
int main() { restult = 7.0 / 22.0; printf("the result is %d\n", result); return 0; } |
Exercise 1
Write a program to computer the area andperimeter of a rectangle with a width of 3 inches and a height of 5 inches. Whatchanges must be made to the program so that it works fo a rectangle with awidth of 6.8 inches and a length of 2.3 inches.
Exercise 2
Write a program that deliberately makes thefollowing mistakes;
Prints a floating-point number using the %dconversion.
Prints an integer using the %f conversion.
Prints a character using the %d conversion.
2Enumeration types
An enumeration type is a distinct integertype with enumerators representing integer values starting from 0. The integer value of an enumerator can alsobe assigned explicitly. An enumeration type can be identified by an optionaltag name. the declaration of enumerationtypes and variables are as in the following examples;
Enum suit{clubs, diamons, hearts, spades};//clubs=0, diamonds=1, hearts=2, spades=3
Enum suit card; //a variable of type suit
Enum Boolean{false, true, uncertain = -1}a, b; // define two variables a and b
A = false;
B=uncertain
Enum{a=6, b,c=3,d=2*b} x,y;
a=6,b=7,c=3,d=14
#include <stdio.h>
int main( int argc, char *argv[] ) { enum suit{clubs, diamonds, hearts, spades}; //clubs = 0, diamonds = 1, hearts = 2, spades = 3 enum suit card; // a variable of type suit card = diamonds; if(card == clubs) { printf("clubs is selected!\n"); } else if(card == diamonds) { printf("diamonds is selected!\n"); } else if(card == hearts) { printf("hearts is selected!\n"); } else { printf("spades is selected!\n"); } return 0; } |
#include <stdio.h>
int main() { enum WEEKDAY {Sunday, Monday, Tuesday, Wednsday, Thursday, Friday, Saturday}; enum WEEKDAY today; // a variable of type WEEKDAY int val = 0; scanf("%d", &val); today = val; if(today == Sunday) { printf("I am going to travel!\n"); } else if(today == Monday) { printf("This is Monday\n"); } else { printf("Test today\n"); } return 0; } |
3array types
An array lets you declare and work with acollection of values of the same type.
For example, you might want to create acollection of five integers, one way to do it would be declare five integers directly:int a, b, c,d ,e
This is of, but what if you needed athousand integers?
An easier way is to declare an array offive integers: int a[5];
The five separate integers inside thisarray are accessed by an index, all arrays start at index zero an go to n-1 in C,thus , int a[5]; contains five elements. For example:
Int a[5]; a[0]=12; a[1]=9; a[2]=14; a[3]=5;a[4]=1;
Example: computes the total an average offive numbers
#include <stdio.h>
float data[5]; /* data to average and total */ float total; /* the total of the data items */ float average; /* average of the item */ int main() { data[0] = 34.0; data[1] = 27.0; data[2] = 45.0; data[3] = 82.0; data[4] = 22.0; total = data[0] + data[1] + data[2] + data[3] + data[4]; avarage = toatal / 5.0; printf("Total %f Avarage %f\n", total, avarage); return 0; } |
This program output
Total 210.000000 Avarage 42.000000
Example3
#include <stdio.h>
int main() { int a[5]; int i; for(i = 0; i < 5; i ++) { a[i] = i; } for(i = 0; i < 5; i ++) { printf("%d, %d\n",i, a[i]); } return 0; } |
An array can be declared withinitialization as in the following example
Int int_array[] = {2, 5, 3, 4};
When an array is initialized withdeclaration, the number of members may be omitted, which is determined by theinitialization.
Array members are accessed by the subscriptoperator, for instance, int_array[2] is the member of the array int_array withindex 2, indices of an array always start from 0
Multidimensionalarrays
Arrays can have more than one dimension,the declaration for a two-dimensional array is:
Type variable [size1][size2]; /*comment*/
For example
Int matrix[2][4]; /* a typical matrix */
To access an element of the matrix, we use thenotation
Matrix[1][2] = 10;
C allows the programmer to use as manydimensions as needed(limited only by the amount of memory available) additionaldimensions can be tacked on
Four dimensions[10][12][9][5]
Example:
#include <stdio.h>
int array[3][2]; /* array of numbers */
int main() { array[0][0] = 0 * 10 + 0; array[0][1] = 0 * 10 + 1; array[1][0] = 1 * 10 + 0; array[1][1] = 1 * 10 + 1; array[2][0] = 2 * 10 + 0; array[2][1] = 2 * 10 + 1;
printf("array[%d]", 0); printf("%d ", array[0][0]); printf("%d ", array[0][1]); printf("\n")
return 0; } |