Introduction to
computer programming – C
Lecture 2
Variables
Variable
A variable is a named data storage location a computer's
memory. By using a variable's name in your program, you are, in
effect, referring to the data stored there.
Variable Names
To use Variables, you need to have variable names.
Follow the following rules while writing variable names
The name can contain letters, digits, and the underscore character
(_).
The first character of the name must be a letter. The underscore is
also a legal first character, but its use is not recommended.
Case matters (that is, upper- and lowercase letters). Thus, the
names count and Count refer to two different variables.
C keywords can't be used as variable names. A keyword is a word
that is part of the C language.
Examples of variable names
present, hello, y2x3, r2d3, ...
_1993_tar_return
Hello#there
double
2fartogo
/* OK */
/* OK but don‟t */
/* illegal */
/* shouldn‟t work */
/* illegal */
NOTE: C IS CASE SENSITIVE SO CSC1205
AND csc1205 are different
C Variables Names …….
Suggestions regarding variable names
DO: use variable names that are descriptive
DO: adopt and stick to a standard naming convention
sometimes it is useful to do this consistently for the
entire software development site
AVOID: variable names starting with an underscore
often used by the operating system and easy to miss
AVOID: using uppercase only variable names
generally these are pre-processor macros (later)
C Basic Data types
There are only a few basic data types in C
char: a single byte, capable of holding one
character
int: an integer of fixed length, typically reflecting the
natural size of integers on the host machine (i.e., 32
or 64 bits)
float: single-precision floating point
double: double precision floating point
C Basic Types
A typical 32-bit machine
Type Keyword Bytes Range
character char 1 -128...127
integer int 4 -2,147,483,648...2,147,438,647
short integer short 2 -32768...32367
long integer long 4 -2,147,483,648...2,147,438,647
long long integer long long 8 -9223372036854775808 …
9223372036854775807
unsigned character unsigned char 1 0...255
unsigned integer unsigned int 2 0...4,294,967,295
unsigned short integer unsigned short 2 0...65535
unsigned long integer unsigned long 4 0...4,294,967,295
single-precision float 4 1.2E-38...3.4E38
double-precision double 8 2.2E-308...1.8E308
Example: Variable types
//a c program to tell the size of variable types in bytes
#include <stdio.h>
main() {
//sizeof() is one of the library functions in C
printf( "\nA char is %d bytes", sizeof( char ));
printf( "\nAn int is %d bytes", sizeof( int ));
printf( "\nA short is %d bytes", sizeof( short ));
printf( "\nA long is %d bytes", sizeof( long ));
printf( "\nAn unsigned char is %d bytes", sizeof( unsigned char ));
printf( "\nAn unsigned int is %d bytes", sizeof( unsigned int ));
printf( "\nAn unsigned short is %d bytes", sizeof( unsigned short ));
printf( "\nAn unsigned long is %d bytes", sizeof( unsigned long ));
printf( "\nA float is %d bytes", sizeof( float ));
printf( "\nA double is %d bytes\n", sizeof( double ));
return 0;
}
Variable declaration
A variable is only used after declaration, this tells the compiler about
the name and type.
The compiler generates an error if you use a variable name that is
not declared.
Variables are declared within the main() function.
Variable declaration syntax 1
Typename variableName;
int count, number, start; /* three integer variables */
float percent, total; /* two float variables */
int x=3; /*declaration and initialization*/
- Initialization is the assignment of a first value to a variable
Typedef keyword
The typedef keyword is used to create a new name for an existing
data type. In effect, typedef creates a synonym. For example, the
statement
typedef int integer;
creates integer as a synonym for int. You then can use integer to
define variables of type int, as in this example:
integer count;
Note that typedef doesn't create a new data type; it only lets you
use a different name for a predefined data type. The
most common use of typedef concerns aggregate data types.
Initializing Numeric Variables
When you declare a variable, you instruct the compiler to set aside storage space for
the variable. However, the value stored in that space--the value of the variable--isn't
defined. It might be zero, or it might be some random "garbage "value.
variable declaration by using an assignment statement, as in this example:
int count; /* Set aside storage space for count */
count = 0; /* Store 0 in count */
(=) sign, which is C's assignment operator
If you write x = 12 in an algebraic statement, you are stating a fact: "x equals 12." In
C, however, it means something quite different: "Assign the value 12 to the variable
named x."
You can also initialize a variable when it's declared. To do so, follow the variable
name in the declaration statement with an equal sign and the desired initial value:
int count = 0;
double percent = 0.01, taxrate = 28.5;
Be careful not to initialize a variable with a value outside the allowed range. Here are
two examples of out-of-range
Constants
Like a variable, a constant is a data storage location used by your
program. Unlike a variable, the value stored in a constant can't be
changed during program execution.
C has two types of constants, each with its own specific uses.
1.Literal constants: It is a value typed directly whenever
its needed e.g
int count = 20;
float discount = 0.28;
They can also be written using scientific notation (number and exponent) e.g
1.23E2
4.08e6
1.23 times 10 to the 2nd power, or 123
4.08 times 10 to the 6th power, or 4,080,000
0.85e-4 0.85 times 10 to the -4th power, or 0.000085
Example: Literal Constants
A variable declared as a constant cant be changed during program
execution
const int count = 100;
const float pi = 3.14159;
const long debt = 12000000, float tax_rate = 0.21;
Constants
2.Symbolic Constants
A symbolic constant is a constant that is represented by a name
(symbol) in your program.
Whenever you need the constant's value in your program, you use its
name as you would use a variable name.
The actual value of the symbolic constant needs to be entered only
once, when it is first defined.
Its advantage is that its easy to reuse a variable e.g PI=22/7 can be
defined and easily used in geometry. (circumference = 3.14159 * (2 *
radius);)
C has two methods for defining a symbolic constant:
#define directive
const keyword.
Symbolic Constants
The #define directive is one of C's preprocessor directives, The
#define directive is used as follows:
#define CONSTNAME literal
The name of a symbolic constant is in UPPER CASE
To define PI as a constant, u would write;
#define PI 3.14159
Example program using constants
/* Demonstrates variables and constants */
#include <stdio.h>
/* Define a constant to convert from pounds to grams */
#define GRAMS_PER_POUND 454
/* Define a constant for the start of the next century */
const int NEXT_CENTURY = 2000;
/* Declare the needed variables */
long weight_in_grams, weight_in_pounds;
int year_of_birth, age_in_2000;
main() {
/* Input data from user */
printf("Enter your weight in pounds: ");
scanf("%d", &weight_in_pounds);
printf("Enter your year of birth: ");
scanf("%d", &year_of_birth
);
/* Perform conversions */
weight_in_grams = weight_in_pounds * GRAMS_PER_POUND;
age_in_2000 = NEXT_CENTURY - year_of_birth;
/* Display results on the screen */
printf("\nYour weight in grams = %ld", weight_in_grams);
printf("\nIn 2000 you will be %d years old\n", age_in_2000);
return 0;
}
Formatted Printing with printf ( )
The printf function is used to output information (both data from variables
and text) to standard output.
A C library function in the <stdio.h> library.
Takes a format string and parameters for output.
printf(format string, arg1, arg2, …);
e.g. printf("The result is %d and %d\n", a, b);
The format string contains:
Literal text: is printed as is without variation
Escaped sequences: special characters preceded by \
Conversion specifiers: % followed by a single character
Indicates (usually) that a variable is to be printed at this location in the
output stream.
The variables to be printed must appear in the parameters to printf
following the format string, in the order that they appear in the format string.
Formatted Printing with printf: Conversion
Specifiers
Specifier Meaning
%c
%d
%x
%f
%e
%s
%u
%%
%ld, %lld
Single character
Signed decimal integer
Hexadecimal number
Decimal floating point number
Floating point in “scientific notation”
Character string (more on this later)
Unsigned decimal integer
Just print a % sign
long, and long long
There must be one conversion specifier for each argument being printed out.
Ensure you use the correct specifier for the type of data you are printing.
Formatted Printing with printf (): Escape
Formatted Printing with printf ( )
An example use of printf
#include <stdio.h>
int main() {
int ten=10,x=42;
char ch1='o', ch2='f';
printf("%d%% %c%c %d is %f\n", ten,ch1,ch2,x,
1.0*x / ten );
return 0;
}
What is the output?
Reading Numeric Data with scanf ()
The scanf function is the input equivalent of printf
A C library function in the <stdio.h> library
Takes a format string and parameters, much like printf
The format string specifiers are nearly the same as those
used in printf
Examples:
scanf ("%d", &x);
scanf ("%f", &rate);
/* reads a decimal integer */
/* reads a floating point value */
The ampersand (&) is used to get the “address” of the variable
All the C function parameters are “passed by value”.
If we used scanf("%d",x) instead, the value of x is passed. As a
result, scanf will not know where to put the number it reads.
Reading Numeric Data with scanf ()
Reading more than one variable at a time:
For example:
int n1, n2; float f;
scanf("%d%d%f",&n1,&n2,&f);
Use white spaces to separate numbers when input.
5 10 20.3
In the format string:
You can use other characters to separate the numbers
scanf("value=%d,ratio=%f", &value,&ratio);
You must provide input like:
value=27,ratio=0.8
Reading Numeric Data with scanf ()
One tricky point:
If you are reading into a long or a double, you
must precede the conversion specifier with an
l (a lower case L)
Example:
int main() {
int x;
long y;
float a;
double b;
scanf("%d %ld %f %lf", &x, &y, &a, &b);
return 0;
}
Type Conversion
C allows for conversions between the basic types, implicitly or
explicitly.
Explicit conversion uses the cast operator.
Example 1:
int x=10;
float y, z=3.14;
/* y=10.0 */
/* x=3
/* x=-3
*/
-- rounded approaching zero */
y=(float) x;
x=(int) z;
x=(int) (-z);
Example 2:
int i;
short int j=1000;
i=j*j;
i=(int)j * (int)j;
/* wrong!!! */
/* correct */
Implicit Conversion
If the compiler expects one type at a position, but another type is
provided, then implicit conversion occurs.
Conversion during assignments:
char c = 'a';
int i;
i=c; /* i is assigned the ASCII code of „a‟ */
Arithmetic conversion – if two operands of a binary operator are
not the same type, implicit conversion occurs:
int i=5 , j=1;
float x=1.0 , y;
y = x / i;
y = j / i;
y = (float) j / i;
/* y = 1.0 / 5.0 */
/* y = 1 / 5 so y = 0 */
/* y = 1.0 / 5 */
/* The cast operator has a higher precedence */
Homework
As an engineer designing a rectangular beam, you need to calculate
its dimensions to ensure it can safely support a specific weight.
Write a program that allows entry of the width and height of the
beam, and it calculates the area (important for material needs) and
the aspect ratio (length divided by width, crucial for structural
stability) to guide your design decisions.
Your friend, who lives in a country that uses Fahrenheit for
temperature, is visiting you. They're struggling to understand the
local weather forecast in Celsius. Write a program that allows them
to easily convert temperatures from Celsius to Fahrenheit, helping
them understand the weather conditions during their visit.