Ics 2102 Lecture 2
Ics 2102 Lecture 2
COMPUTER PROGRAMMING.
C VARIABLES.
A variable- is a name given to a memory location inside our computer where we can store
data.
They are containers for storing data values like numbers and characters.
Creating variables.
There are 2 methods of creating a variable;
1.Declaration method
int age; //declare a variable
age = 22; //assign a value to the variable
2.Initialization method.- from the word initial, refers to assigning an initial value to a variable
int age = 22;
The Syntax for creating a variable is;
type variableName = value;
Where type is one of the C data types(such as int), and variableName is the name of the
variable such as x or age, The equal sign is used to assign a value to a variable.
Printing out integer variables.
Printf(“%d”, age);
%d is a format specifier- value of age replaces %d.
Printf(“Age: %d”, age); //optimizing the printf statement for readability
C Format specifiers
They are used together with printf() function to tell the compiler what type of data the variable is
storing. It is basically a place holder for the variable value.
A format specifier starts with a % sign followed by a character.
It is surrounded by double quotes.
To combine both text and a variable, separate them with a comma inside the printf() function:
int myAge = 18;
Printf(“My age is : %d”, myAge);
Operations that can be performed on variables
Change value of variables.
int age = 22; // age is 22
Age = 30; //the new value of variable age
Printf(“\nNew age : %d”, age); //output will be 30
Assigning value of one variable to another variable.
int age = 20;
int secondage = 22;
age= mysecondage //value of second age becomes 22.
Copy values of empty variables.
int number =10;
int secondNumber;
secondNumber = number; // assign the value of number to secondnumber
//secondnumber now has the value 10.
Add variables together.
To add one variable to another use the operator +
int x = 5;
Int y = 6;
int sum = x + y;
printf(“%d”, sum); //output is 11
Declaring multiple variables at once.
Use a comma when declaring multiple values:
int x = 5,y = 6,z = 10;
printf(“%d”, x + y + z);//output is 21
You can also assign the same value to multiple variables of the same type:
int x, y, z:
x = y = z = 10;
Printf(“%d”, x + y + z); //output will be 30
VARIABLE NAMING CONVENTION.
Variables names are normally unique and they are called identifiers.
Use descriptive names to name variables. EG: firstNumber, myAge
Camel case format. First word starts with a small letter, the rest of the words begin with upper case
letters, eg secondNumber.
Rules;
Can contain letters, digits and underscore.
No spaces between variables names.
Case sensitive. E.g. num and NUM are different variables,
Cannot start a variable name using a number.
Cannot use reserved keywords. Which are special names used in the C syntax e.g. if.
Quiz:
Can you guess the output of this program?
#include <stdio.h>
int main(){
Int number1 = 2;
Printf(“%d ”, number1);
Printf(“%d”, number1);
return 0;
}
Practical example;
A program to calculate the area of a rectangle(by multiplying length and width):
#include<stdio.h>
int main(){
//create integer variables
int length = 4;
int width = 5;
int area;
return 0;
IDENTIFIERS AND KEYWORDS
Keywords/reserved/predefined words.
They are 32 words in ANSIC. E.g. break, goto, if, for, continue, while, do, switch, auto, double.
Keywords cannot be used as identifiers.
They are always in lower case letters.
Identifiers.
Refer to names of variables, arrays, structures, union.
May contain letters, numbers and underscores.
Length of an identifier is 31 characters.
DATA TYPES
Data types- specify/determine the type of the data that can be stored in a variable and the size of memory
for that data.
Types.
1) Primary/fundamental/built in data types. E.g. int, float, char, double, void
2) Derived data types. E.g.. arrays, structures, pointer union
3) User defined data types E.g. typedef, enumerated data types
Example of typedef.
typedef int Fayee;
Fayee a;
PRIMARY DATA TYPES.
NUMERIC DATA TYPES.
INTEGERS.
Int:- stores whole numbers, without decimals.
Short int- upto 2 bytes
Long int- upto 4 bytes= 32 bits
Signed integers – take both positive and negative value
Unsigned integers- no positive or negative signs. Only positive values.
For a 16 bit machine- signed int can hold from -32768 to 32767.
For a 32 bit machine- from -2147483648 to +2147483647.(2 raised to power 32 distinct values.)
Format specifiers.
Int (%d)
Unsigned int (%u)
Long int (%dd)
Unsigned long int (%lu)
Signed short int (%hi)
Unsigned short int (%hu)
Double and float data type.
They store decimal and exponential values(floating point numbers).
Difference is in the size; double- 8 bytes, float- 4 bytes.
Range of float 3.4e39 to 3.4e38
Example of float is; Float weight = 20.00;
printf(“%f”, weight);
Float takes 6-7 digits after the decimal point so it fills the rest with random values.
So it would print out 20.000000.
Double stores numbers with more precision.
double- 8 bytes.
To avoid printing out many digits after the decimal point use a dot(.) before f, followed by the
number of digits you would want after the decimal point , within the format specifier eg %.2f…
would return 2 digits after the decimal point. Or %.4lf for double values.
Long double holds upto 10bytes
-takes upto 15 digits after the decimal point.
Format specifier is %lf.
float money = 20.00f;
Printf(“%f”, money);
Double is also used to store exponential numbers or scientific numbers with an e to indicate power of
10.
double = 5.5e6
This means 5.5 into 10 power 6.
Suggestion: Use double for calculation since it stores decimal numbers with more precision.
CHARACTER DATA TYPE
This is used to store a single character, which must be surrounded by single quotes.
Size: 1 byte.
Format specifier :%c
Example:
char myGrade = ‘A’;
printf(“%c”, myGrade);
Also, one can use ASCII values to display some characters. Eg A = 65 in ASCII.
Example:
Char a = 65;
Printf(“%c”, a); //outputs A
Characters can either be signed(-128 to 127) and unsigned(0 to 255).
Characters are internally stored as integers.
Note: Do not use char data type to store multiple characters at once, like
char myText = ‘hello’ // this will produce an error.
Void data type.
Means empty.
Not used with variables. Used with functions that don’t return any values.
Example to demonstrate variables and data types;
#include <stdio.h>
int main()
{
double weight = 40;
printf("%.4lf\n", weight);
return 0;
} // output will be 1
Practical examples.
A program that calculates and prints out the total cost of items purchased.
#include <stdio.h>
int main(){
//create different variables
int items = 50;
float costPerItem = 10.10;
float totalCost = items * costPerItem;
char currency = '$';
//print variables
printf("Number of items: %d\n", items);
printf("Cost per item: %.2f%c\n", costPerItem, currency);
printf("Total cost = %.2f%c", totalCost, currency);
return 0;
}
CONSTANTS IN C
C constants have fixed values.
Symbolic constants
Numeric constants
Integer constants; - Cannot use special characters or space between digits. Just + or -
decimal- 0-9 base 10.
Octal- 0-7 base 8.
Hexadecimal- 0-15 base 16. e.g. 0X14. They start with OX or Ox . From 0-9 and A to F, where A is
10.
Floating- point/real constants- numbers with decimal points e.g. 12.45. Can also use + or -.
Character constants
Single character constants- enclosed in single quotation marks e.g. ‘A’. Stored in the form of
ASCII values like A – Z= 65-90. a-z = 97-122. 0-9 = 48-57. Special characters 0-47,58-64,91-96.
-String constants – sequence of characters enclosed in double quotation marks. Can be letters,
numbers, special characters.
Declaring constant variables.
Use const key word.
const int a = 10;
const minutesPerHour = 60;
Use of symbolic constant.
#define A 10
#define PI 3.14
Note: use upper case letters to declare e.g. PI, A.