Unit 3 – The Basics of C: Variables, Arithmetic Operations, Math Functions,
Input/Output
Purpose: Learn basic structure of a C program and how to display words and numbers on
the screen, how to handle variables and to perform arithmetic calculations.
Lesson 3_1 – Data and Variables (1)
Topics:
· Naming variables
· Declaring data types
· Using assignment statements
· Displaying variable values
· Elementary assignment statements
Problem 5: Write a program to read a Centigrade temperature and convert it to
Fahrenheit using the formula
Algorithm
1. Input Centigrade temperature (temp_c)
2. Convert to Fahrenheit (temp_f); this is consider the output of this program
3. Print both temperatures
Source Code
/* A program to convert a Centigrade temperature to Fahrenheit */
#include <stdio.h>
#include <conio.h> /*so that we can use getch*/
void main(void)
{ /*begin of main*/
/* Variable Declarations */
int problem_no;
float temp_c, temp_f;
problem_no = 5;
printf(“output of problem%3d\n”, problem_no);
/* Stores the value of Centigrade temperature in temp_c */
temp_c = 17.0;
/* Converts it and stores it in temp_f */
temp_f = 9.0 * temp_c/5.0 + 32.0;
/* Prints both temperatures values stored in memory cells temp_c and temp_f */
printf(“C =%9.2f, F = %9.2f”, temp_c, temp_f);
getch(); /*to make the output wait for a keypress*/
} /* end of main*/
Output
output of problem 5
C = 17.00, F =62.60
1. What are variables in a program?
In the context of computer programming, a variable indicates a storage location (i.e. memory cell) where we can store different data or values. The standard simple types of values we can store in a variable are: integers (e.g., -2, -1, 0, 1, 2), real (e.g., 3.55, 0.0, 187E-02, 35.997E+11), boolean (boo_lee_an) values, sometimes called logical values, have one of two values – false or true, characters - letters, puncutation marks, or digit characters- that appear on the keyboard
2. What is a constant?
A variable whose value is sealed and its value can be looked at but it’s not possible to replace it’s called a constant (e.g., pi = 3.14, zero_f = 32.0, e = 2.78).
3. How do we declare variables?
Variable names in C must be declared. The statement
int problem_no
declares the variable problem to be of the int type which means integer and must be typed in lower-case). An int type data does not contain a decimal point.
4. How do we declare more than one variable?
Variables of the same type may be declared in the same statement. However, each of them must be separated from the other by a comma, e.g., the statement
float temp_c, temp_f
declares the variables temp_c and temp_f to be of the float (which must be typed in lower case) type (see Fig 3_1a). A float type data contains a decimal point with or without a fraction. For example, 1., 1.0, and 0.6 are float type data. When data without a decimal point is assigned to a float type variable, the C compiler automatically places a decimal point after the last digit.
5. What is the effect of declaring variables?
It causes the C compiler to know that space is to be reserved in memory for storing the values of the variables. By stating a variable’s type, the C compiler knows how much space in memory is to be set aside. Although not explicitly set by the ANSI C standard, the standard implies the minimum number of bits to be used for each variable type. For instance, ANSI C requires that type int be capable of handling a range of –32767 to 32767 variable month as int indicates that 16 bits or 2 bytes of memory should be reserved for this variable’s value. On the other hand, a float type value typically occupies 4 bytes or 32 bits. Thus, declaring a variable to be a float requires 4 bytes of memory to be reserved.
In addition, C uses different types of binary codes for integers and reals. This means that, for example, the bit pattern for 32 stored as an int is completely different from the bit pattern for storing 32. as a float. It is important that we keep this in mind. Forgetting this fact will lead to errors. For instance if printf attempts to read a memory cell that contains an int but it expects a float to be in the cell it will misinterpret the cell contents and print out something completely wrong. Since it is us, the programmers that tells printf what to expect in a memory cell, we must tell it correctly. Later in this lesson we will describe how we indicate to printf what to expect in a memory cell.
6. How do we name variables?
Variables in C programs are identified by name. Variable names are classified as identifiers. Therefore, the naming convention for variables must obey the rules used by identifiers. For instance, the first character of an identifier cannot be numeric. For the first and other characters the requirements are:
Component / RequirementThe 1st character in identifier / Must be non-digit characters a-z, A-Z, or _
The other characters in identifier / Must be non-digit characters a-z, A-Z, _, or digit characters 0-9
In addition, there are other constraints on creating valid identifiers. These are:
Topic / CommentThe maximum number of characters in an internal identifier (i.e., identifier within a function. / ANSI C allows a maximum number of 31 characters for names of internal identifier.
Use C reserved words, also called keywords, as identifiers. / Not allowed, i.e., do not use float, int,…, etc. A complete list of reserved words is:
auto / break / case
char / const / continue
default / do / double
else / enum / extern
float / for / goto
if / int / long
register / return / short
signed / sizeof / static
struct / switch / typedef
union / unsigned / void
volatile / while
You cannot use any of the above words as an identifier.
Use of standard identifiers such as printf. / Allowed. However it is not recommended that standard identifiers be used as variable names because it is very confusing.
Use of uppercase characters or mixed-case characters. / Allowed. However, many programmers use lower-case characters for variable names and uppercase for constant names. Differentiate your identifiers by using different characters rather than different cases.
Use of blank within an identifier. / Not allowed because an identifier is a token.
· Examples of illegal variable names
1apple interest_rate float In come one.two
· Examples of legal variable names
apple1 interest_rate xfloat Income one_two
7. As a program begins to execute, what conceptually is happening in memory?
Conceptually, a table is created internally. This table contains variable names, types, addresses and values. The names, types and addresses are first established essentially during compilation, then as execution takes place space is reserved in memory and the variable values are put into the memory cells reserved for the variables. For instance, after the first three assignment statements have been executed in this lesson’s program, the table looks like the following (note that the memory cell addresses are written in hexadecimal notation – these are not necessarily real addresses, they are simply examples):
Variable name / Variable type / Memory cell address / Variable valuemonth / int / FFF8 / 12
expense / float / FFF6 / 111.1
income / float / FFF2 / 100.
After the fourth and fifth assignment statements have been executed, the table becomes:
Variable name / Variable type / Memory cell address / Variable valuemonth / int / FFF8 / 11
expense / float / FFF6 / 111.1
income / float / FFF2 / 82.1
Note: You do not need to be concerned about the memory cell addresses at this point.
The addresses are automatically set when you compile and execute your programs.)
You will find that your programs’ purpose is to continually change the values in the variable table.
8. What is an assignment statement?
An assignment statement assigns a value to a variable, meaning an assignment statement causes a value to be stored in the variable’s memory cell. For example, the statement
problem = 5
assigns the integer value 5 to int type variable problem. It causes 5, written in two’s complement binary type of notation, to be stored in the problem memory cell.
In C, a simple assignment statement takes the form of
variable_name = value;
where this statement assigns the value on the right side of the equal sign to the variable on the left side of the equal sign. The binary representation of the value is stored in the variable’s memory cell after the assignment has taken place. The value can be a constant,
a variable with a known value, or other, such as a function or an expression which returns a value. Note that the equal sign in an assignment statement does not purely mean equal. As you become exposed to more programming techniques you will need to interpret an assignment statement by thinking of the table of variable values created, and the storing of values in the memory cells rather than the term “equal”.
9. How do we display the value of a variable or constant on the screen?
The printf() function can be used to display the value of a variable or constant on the screen. The syntax is:
printf(format string, argument list);
where the format string is a string literal that contains three types of elements. The first one is referred to by ANSI C as plain characters. These are characters that will be displayed directly unchanged to the screen. The second one is conversion specification(s) that will be used to convert, format, and display argument(s) from the argument list. The third is escape sequences that the printf function uses to control the cursor or insertion point. Each argument must have a format specification. Otherwise, the results will be unpredictable. For example, in the statement
printf(“problem=%5d \n”,problem);
The format string is “problem=%5d =n”. The plain characters problem= will be displayed directly without any modification, but the conversion specification %5d will be used to convert, format, and display the argument, month, on the screen. The escape sequence, \n, moves the insertion point to the next line.
The simplest printf() conversion specifications (also called format specifications) for displaying int and float type values have the following forms:
%[field width]d / e.g., %5d for int%[field width][.precision]f / e.g., %9.2f for float
where format string components enclosed by [] are optional. (The characters [ and ] are not the part of the format string.) The field width is an integer representing the minimum number of character spaces reserved to display the entire argument (including the decimal point, digits before and after the decimal point and sign). The precision is an integer representing the maximum number of digits after the decimal point. For example %5d will reserve 5 blank spaces for displaying an int type data, %9.2f will reserve a total of 9 blank spaces for a float type data and 2 digits will be displayed after the decimal point. These concepts are shown in Fig 3_1c. If your actual input data contain fewer digits after the decimal point, the C compiler will add additional zero(s) after the decimal point when displaying it.
Quiz 3_1
1. True or False:
a. The following int type variable names are legal:
1cat, 2dogs, 3pears, %area
b. The following float variable names are legal:
cat, dogs2, pears3, cat_number
c. 5d or %8D are legal format specifications for an int type variable or constant
d. 6.3f or %10.1F are legal format specifications for a float type variable
e. The two statement below are identical:
int ABC, DEF;
int abc, def;
2. Which of the following are incorrect C variable names, and why?
enum, ENUM, lotus123, A+B23, A(b)c, AaBbCc, Else, ab,c pi, p
3. Which of the following are incorrect C assignment statements, and why?
year = 1967
1967 = oldyear;
day = 24 hours;
while = 32;
3. Suppose year is an int variable and salary is a float variable, which of the following printf() statements are unacceptable, and why?
printf (“My salary in 1997 is $2000”, salary);
printf(“My salary in 1997 is %d\n”,salary);
printf(In year %d, my salary is %f\n”), year, salary;
printf(“My salary in %d year is %f\n, salary,year”);
printf(“My salary in %5d year is %10.2f\n\n”,year,salary);
4. The price of an apple is 50 cents, a pear 35 cents, and a melon 2 dollars. Write a program to display the prices as follows:
***** ON SALE *****
Fruit type Price
Apple $ 0.50
Pear $ 0.35
Melon $ 2.00
Lesson 3_2 – Data and Variables (2)
Topics:
· Using the define directive to define constants
· More about conversion specifications and their components
· Scientific notation
· Flags in conversion specifiers
Problem 6: Write a program that 1) identifies the days of the year (DAYS_IN_YEAR)
and p (PI) as constants, 2) prints the DAYS_IN_YEAR constant value using 1d, 9d, and d field widths, 3) prints the real number 123456789.12 stored in variable income and PI in various floating point (e.g., decimal notation) and scientific notation (e.g., 5.765 × 107 = 5.765E + 007).
Source Code
#include <stdio.h>