Programming Fundamentals: Lecture # 4 Nauman Riaz Chaudhry
Programming Fundamentals: Lecture # 4 Nauman Riaz Chaudhry
Programming Fundamentals: Lecture # 4 Nauman Riaz Chaudhry
Programming
Fundamentals
Lecture # 4
Nauman Riaz Chaudhry
[email protected]
[email protected]
1
Course Notes
http://www.its.strath.ac.uk/courses/c/
2
Bits, bytes and memory
Your computer's memory can
0
Address
be seen as a sequence of cells.
Each cell is 8 bits (one byte) 1
large. Data is stored by setting 2
these bits to 1s and 0s. stored
3
Each cell has an address. You bytes
4
don't need to know (or care to
know) what this address is. 5
Your system uses the address
to locate the data stored there.
3
Variables
We need to be able to store data in memory, during
the execution of our program.
We also need to be able to access and even modify
this data.
Solution : variables
A variable is a reserved location in memory that
has a name
has an associated type (for example, integer)
holds data which can be modified
4
Variables
In order to use a variable in our program we must
first declare it.
HOW?
A declaration statement has the format:
type variable_name ;
type : what kind of data will be stored in that location
(integer? character? floating point?)
variable_name : what is the name of the variable?
semi-colon : this is a statement!
WHERE?
At the beginning of a function, right after the opening brace.
5
Variable names
In C, variable names are built from
the letters of the alphabet
the digits 0 through 9
the underscore
A variable name
must start with a letter or an underscore
A variable name
must not be the same as a reserved word
used by the C language.
Only the first 31 characters of a variable name are
significant. The rest are ignored.
6
Variable names
Selecting good variable names is important for
program readability.
#include <stdio.h>
int main () {
int num_students;
return 0;
} 9
Variable values
After a variable has been declared, its memory location
contains randomly set bits. In other words, it does not
contain valid data.
The value stored in a variable must be initialized
before we can use it in any computations.
There are two ways to initialize a variable:
by reading its value from the keyboard using scanf
by assigning a value using an assignment statement
(more on that later)
10
Keyboard input: scanf()
scanf() will scan formatted input from the keyboard.
It uses special format specifiers that specify the type
of the variable whose value is to be read from the
keyboard.
To read an integer:
int num_students;
scanf("%d", &num_students);
To print a message:
printf("This is a message\n");
12
Printing variable values
To print an integer:
#include <stdio.h>
int main () {
int num_students;
printf("How many students are there? ");
scanf("%d", &num_students);
printf("There are %d students.\n");
return 0; 14