0% found this document useful (0 votes)
105 views

Variable and Data Types

This document discusses key concepts related to variables in C programming including declaring variables, variable types like int and double, assigning values to variables using assignment statements, and initializing variables before use to avoid bugs. It provides examples of declaring, assigning, and initializing different variable types like integers and floating point numbers and simulating a simple program to calculate area step-by-step.
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
105 views

Variable and Data Types

This document discusses key concepts related to variables in C programming including declaring variables, variable types like int and double, assigning values to variables using assignment statements, and initializing variables before use to avoid bugs. It provides examples of declaring, assigning, and initializing different variable types like integers and floating point numbers and simulating a simple program to calculate area step-by-step.
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 32

Lecture 3:

Variables, Values, and Types

C-1
Overview
Concepts this lecture:
Variables
Declarations
Identifiers and Reserved Words
Types
Expressions
Assignment statement
Variable initialization

C-2
Container

 Container type
 Container Capacity
 Operation over container type

C-3
Review: Memory
Memory is a collection of locations called
variables
In a programming language, we get at the
location by using a variable
Each variable has
A name (an identifier)
A type (the kind of information it can contain)

C-4
Memory and Variables
Memory is a collection of locations called
variables
In a programming language, we get at the
location by using a variable
Each variable has
A name (an identifier)
A type (the kind of information it can contain)
Basic types include
int (integers – whole numbers: 17, -42)
double (floating-point numbers with optional fraction
and/or exponent: 3.14159, 6.02e23)
char (character data: ‘a’, ‘?’, ‘N’, ‘ ’, ‘9’)
Note: ‘9’ is a character; 9 is an integer – they are different
and have different types

C-5
Variable

 The definition of a variable will assign storage for


the variable and define the type of data that will
be held in the location
 So what data types are available?
 int float double char void enum
 Please note that there is not a boolean data type.
C does not have the traditional view about logical
comparison, but that's another story.
 Recent C++ compilers do have a boolean
datatype.

C-6
Basic Datatypes

 Integer (2b)
 Decimal (4b)
 Character (1b)

C-7
Data Type
Int is used to define integer float is used to define floating
numbers. point numbers.
{ {
int Count; float Miles;
Count = 5; Miles = 5.6;
}  }

Double is used to define BIG Char defines characters.


floating point numbers. It {
reserves twice the storage for the char Letter;
number. On PCs this is likely to Letter = 'x';
be 8 bytes. }
{
double Atoms;
Atoms = 2500000;
}

You can find out how much storage is allocated to a data type by
using the sizeof operator.
printf("%d \n", sizeof(int));
C-8
Modifier
The three data types above have the following modifiers.
 short
 long
 signed
 unsigned
The modifiers define the amount of storage allocated to the variable.
The amount of storage allocated is not cast in stone.
ANSI has the following rules
short int <= int <= long int float <= double <= long double

C-9
DataTypes

C-
10
Memory example
Variable declarations in C
int i = 12;
double gasPrice = 1.799;
char bang = ‘!’;
Picture:
i 12 (int)
gasPrice 1.799 (double)
bang ‘!’ (char)

C-11
Declaring Variables
int months;
Integer variables represent whole numbers:
1, 17, -32, 0 Not 1.5, 2.0, ‘A’
double pi;
Floating point variables represent real numbers:
3.14, -27.5, 6.02e23, 5.0 Not 3
char first_initial, middle_initial, marital_status;
Character variables represent individual keyboard
characters:
'a', 'b', 'M', '0' , '9' , '#' , ' ' Not "Bill"

C-12
Variable Names
"Identifiers" are names for things in a program
for examples, names of variables
In C, identifiers follow certain rules:
•use letters, numerals, and underscore ( _ )
•do not begin with a numeral
•cannot be “reserved words”
•are "case-sensitive"
•can be arbitrarily long but...

Style point: Good choices for identifiers can be extremely helpful


in understanding programs
Often useful: noun or noun phrase describing variable
contents

C-13
Reserved words
Certain identifiers have a "reserved"
(permanent, special) meaning in C
• We’ve seen int already
• Will see a couple of dozen more
eventually
These words always have that special meaning,
and cannot be used for other purposes.
• Cannot be used names of variables
• Must be spelled exactly right
• Sometimes also called “keywords”

C-14
Under the Hood
All information in the CPU or memory is actually a series
of ‘bits’: 1’s and 0’s
Known as ‘binary’ data
Amazingly, all kinds of data can be represented in binary:
numbers, letters, sounds, pictures, etc.
The type of a variable specifies how the bits are
interpreted
Binary C type (sample) value
01010001 int 161
char ‘A’
double 10.73

Normally we ignore the underlying bits and work with C types

C-15
Assignment Statements
An assignment statement stores a value into a
variable.
The assignment may specify a simple value to be
stored, or an expression
int area, length, width; /* declaration of 3 variables */
length = 16; /* "length gets 16" */
width = 32; /* "width gets 32" */
area = length * width; /* "area gets length times width" */

Execution of an assignment statement is done in two distinct


steps:
Evaluate the expression on the right hand side
Store the value of the expression into the variable
named on the left hand side

C-16
my_age = my_age+1
This is a “statement”, not an equation. Is there a
difference?
The same variable may appear on both sides of an
assignment statement

my_age = my_age + 1 ;
balance = balance + deposit ;

The old value of the variable is used to compute the value


of the expression, before the variable is changed.
You wouldn’t do this in math!

C-17
Program Execution
A memory location is reserved by declaring a C variable

You should give the variable a name that helps someone


else reading the program understand what it is used for in
that program

Once all variables have been assigned memory locations,


program execution begins

The CPU executes instructions one at a time, in order of


their appearance in the program (we will introduce more
options later)

C-18
An Example
/* calculate and print area of 10x3 rectangle */
#include <stdio.h>
int main(void) {
int rectangleLength;
int rectangleWidth;
int rectangleArea;
rectangleLength = 10;
rectangleWidth = 3;
rectangleArea = rectangleLength * rectangleWidth ;
printf(“%d”, rectangleArea);
return 0;
}

C-19
Hand Simulation
A useful practice is to simulate by hand the
operation of the program, step by step.

This program has three variables, which we


can depict by drawing boxes or making a
table

We mentally execute each of the instructions,


in sequence, and refer to the variables to
determine the effect of the instruction

C-20
Tracing the Program

rectangleLength rectangleWidth rectangleArea

after ? ? ?
declaration
after statement 10 ? ?
1
after statement 10 3 ?
2
after statement 10 3 30
3

C-21
Initializing variables
Initialization means giving something a value for the
first time.
Anything which changes the value of a variable is a
potential way of initializing it.
For now, that means assignment
statement
General rule: variables have to be initialized before
their value is used.
Failure to initialize is a common source of
bugs.
Variables in a C program are not automatically
initialized to 0!

C-22
Declaring vs Initializing
int main (void) {
double income; /*declaration of income, not an
assignment or initialization */

income = 35500.00; /*assignment to income,


initialization of income,
not a declaration.*/
printf ("Old income is %f", income);
income = 39000.00; /*assignment to income, not a
declaration,or initialization */
printf ("After raise: %f", income);

return 0;
}

C-23
Example Problem:
Fahrenheit to Celsius
Problem (specified):
Convert Fahrenheit temperature to
Celsius

C-24
Example Problem:
Fahrenheit to Celsius
Problem (specified):
Convert Fahrenheit temperature to Celsius

Algorithm (result of analysis):


Celsius = 5/9 (Fahrenheit - 32)

What kind of data (result of analysis):


double fahrenheit, celsius;

C-25
Fahrenheit to Celsius (I)
An actual C program

#include <stdio.h>
int main(void)
{
double fahrenheit, celsius;

celsius = (fahrenheit - 32.0) * 5.0 / 9.0;

return 0;
}

C-26
Fahrenheit to Celsius (II)
#include <stdio.h>
int main(void)
{
double fahrenheit, celsius;
printf("Enter a Fahrenheit temperature: ");
scanf("%lf", &fahrenheit);
celsius = (fahrenheit - 32.0) * 5.0 / 9.0;
printf("That equals %f degrees Celsius.",
celsius);
return 0;
}

C-27
Running the Program

Enter a Fahrenheit temperature: 45.5


That equals 7.500000 degrees Celsius

Program trace
fahrenheit celsius

after declaration ? ?
after first printf ? ?
after scanf 45.5 ?
after assignment 45.5 7.5
after second printf 45.5 7.5

C-28
Assignment step-by-step
celsius = (fahrenheit-32.0) * 5.0 / 9.0 ;

1. Evaluate right-hand side


a. Find current value of fahrenheit 72.0
b. Subtract 32.0 40.0
b. Multiply by 5.0 200.0
c. Divide by 9.0 22.2
2. Assign 22.2 to be the new value of celsius
(the old value of celsius is lost.)

C-29
Fahrenheit to Celsius
(III)
#include <stdio.h>
int main(void)
{
double fahrenheit, celsius;
printf("Enter a Fahrenheit temperature: ");
scanf("%lf", &fahrenheit);
celsius = fahrenheit - 32.0 ;
celsius = celsius * 5.0 / 9.0 ;
printf("That equals %f degrees Celsius.",
celsius);
return 0;
}
C-30
Qualifiers
1. Const
The const qualifier is used to tell C that the variable value can not
change after initialisation.const float pi=3.14159;
pi cannot be changed at a later time within the program.
# define pi 3.14159
const int class_size = 40;
1. Volatile
A variable should be declared volatile whenever its value can
be changed by something beyond the control of the program
volatile int var;
int volatile var;
Usage
Memory-mapped peripheral registers
Global variables modified by an interrupt service routine
Global variables within a multi-threaded application
use normally in embedded programming.
Declaration of Storage
1. Class
Auto
1. It is a local variable known only to the function in which it is
declared. Auto is the default storage class.
main{float a=0;}

1. Static
1. Local variable which exists and retains its value even after the
control is transferred to the calling function.
main{ static float a=0;}

1. Extern
1. Global variable known to all functions in the file
main{ extern float a=0;}

• Register
1. Social variables which are stored in the register.
main{ register float a=0;} C-
32

You might also like