0% found this document useful (0 votes)
3 views46 pages

Chap 09

This document covers the fundamental elements of the C programming language, including identifiers, keywords, variables, data types, operators, and expressions. It outlines the rules for naming variables, the types of constants, and the importance of data types in memory allocation. Additionally, it explains various operators and their functions, including arithmetic, relational, and logical operators, as well as the concept of expressions and assignment statements.

Uploaded by

ammarimran2192
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views46 pages

Chap 09

This document covers the fundamental elements of the C programming language, including identifiers, keywords, variables, data types, operators, and expressions. It outlines the rules for naming variables, the types of constants, and the importance of data types in memory allocation. Additionally, it explains various operators and their functions, including arithmetic, relational, and logical operators, as well as the concept of expressions and assignment statements.

Uploaded by

ammarimran2192
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

COMPUTER SCIENCE

12

(MS Access and C)

CHAPTER 9: Elements of C Language

Prof. Shahzeb Malik


Topics

• Identifier and Types of Identifiers


• Keywords
• Variable
• Rules for Naming Variable
• Variable Declaration
• Variable Initialization
• Constant
• Data Types ( Integer, Float & Character)
• Overflow and Underflow
• Problems with floating point numbers

Prof. Shahzeb Malik


Topics (continued)

• Operator and Expression


• Unary and Binary Operators
• Arithmetic Operator and Expression
• Data type of an expression
• Assignment Statement
• Lvalue and Rvalue
• Compound Assignment Statement
• Compound Assignment Operators
• Increment and Decrement Operators
• Relational Operators and Expression

Prof. Shahzeb Malik


Topics(continued)

• Compound Condition
• Logical Operators ( AND, OR & NOT)
• Operator Precedence and Associativity of Operators
• Comments
• Type Casting ( Implicit and Explicit)

Prof. Shahzeb Malik


An identifier is the name given to the variable, constant, function or label in the program.

• descriptive but short


• May consist of 31 characters

Rules for Identifier


• The first character alphabet/ (_) such as _large, age, marks etc.
• The reserved word not allowed such as int, double, break etc.
• Blank space not allowed such as student marks.

Prof. Shahzeb Malik


1. Standard Identifiers
That has special meaning in C. Can be redefined but not recommended

Examples
printf scanf

2. User-defined Identifiers
Defined by the programmer.
• Used to store data and program results

Examples
my_name marks age

Prof. Shahzeb Malik


That has a predefined meaning and purpose.

• reserved words
• Can not be used for another purpose / can not be redefined
• Written in lowercase letters
• The total keywords is 32

List of Keywords

Prof. Shahzeb Malik


• named of memory location or memory cell
• Store input data and results.
• The value can change during program execution but name can’t change
• The variables are created / store in RAM

Prof. Shahzeb Malik


Rules Examples
• include letters, numbers and underscore (_) sub1, f_name, Number1
• First character must be a letter or underscore _ _area , age
• Blank spaces are not allowed My height , total marks
• Special symbols such as @, $, % are not allowed. $cost , tot.al , success!
• Reserved word cannot be used Tax != tax
• Declared only for one data type long, double, void
• up to 31 characters

Prof. Shahzeb Malik


• income Valid.
• double Invalid. A keyword cannot be used as variable name.
• total marks Invalid. A variable cannot have spaces in it.

• averge-score Invalid. A variable cannot have hyphen in it.


• 2ndTry Invalid. A variable cannot start with a digit.
• $cost Invalid. The special symbol $ cannot be used in variable name.
• MAX_SPEED Valid
• My.school Invalid. A variable cannot have a period "." in it.

• room# Invalid. A variable cannot have hash sign in it.

• no_of_students Valid.

Prof. Shahzeb Malik


Specifying the variable name and its type

• All variables must be declared before they are used in the program otherwise compiler
generate error
Syntax
data_type variable_name;
Examples
int marks, total; (list of variables)
double salary;
char grade;

Prof. Shahzeb Malik


Assigning value to a variable at the time of declaration.
• Garbage value
• If a variable declared but not initialized, it may contain meaningless data
Syntax
type_name variable = value;
Examples
int n = 100;
int x = 50, y = 75;
float average = 50.73;
char grade = ‘A’;

Prof. Shahzeb Malik


A quantity that cannot be changed during program execution.
Types of Constants
1. Numeric Constants
Numeric constant consists of numbers. It can be further divided into two types:
a) Integer Constant
Numeric values without fraction or decimal point.
Examples
87 45 -10 -5
b) Floating Point Constants
Numeric values with fraction or decimal point. Examples
50.75 10.22 –13.4

Prof. Shahzeb Malik


2. Character Constants
Any character written within single quotation mark. Min/max length 1.
Examples
‘A’ ‘n’ ‘9’ ‘=’ ‘$’

3. String Constants
A collection of characters written in double quotations mark.
• May consist of any alphabetic characters, digits and special symbols
Examples
“Pakistan” “123” “99-Mall Road, Lahore”

Prof. Shahzeb Malik


The data type specifies the type of data and set of operations that can be applied on the data.
• Every data type has a range of values
• Requires different amount of memory

1. Standard Data Type


A data type that is predefined in the language.
Examples
int float long double char
2. User-defined Data Type
C also allows the user to define his own data types.

Prof. Shahzeb Malik


Integer data is the numeric value with no decimal point or fraction.
• May have positive or negative value
Examples
10 520 -20
Types of Integer Data Type -215 to 215-1

-215 to 215-1

216-1

Remember size in bits

Prof. Shahzeb Malik


The floating point data is a numeric value with decimal point or fraction.
• Also called real number

precision refers the


Examples number of digits after
10.5 5.3 -10.91 the decimal point
Types of Floating point Data Type
float
• precision of 6 decimal places (least accurate)
double
• precision of 15 decimal places
long double
• precision of 19 decimal places

Prof. Shahzeb Malik


char data type is used to store character value.
• Takes 1 byte in memory
• Used to represent:
• Letter a - z and A - Z
• Numbers 0-9
• Space (blank)
• Special characters , . ; ? “ / ( ) [ ] { } * & % ^ < > etc.

• Given in single quotes E.g. ‘A’, ‘*’

• Can perform mathematical operation on character values

Prof. Shahzeb Malik


• Overflow occurs when value assigned to the variable is more than the maximum possible value
• Example - The maximum value for int type variable is 32767. If the assigned value is more than
32767, then an integer overflow occurs

• An underflow occurs when the value assigned to a variable is less than the minimum possible value
• Example - The minimum value for int type variable is –32768. If the assigned value is less than
-32768, then an integer underflow occurs

• Not detected by the compiler


• Program may produce wrong result.

Prof. Shahzeb Malik


• Cancellation error
• Applying an operation to a large number and a small number
e.g., 1000.0 + 0.0000001234 is equal to 1000.0

• Arithmetic Underflow
• is an error in which a very small computational result is represented as zero
e.g., 0.00000001 * 10-1000000 is equal to 0

• Arithmetic Overflow
• is an error in which the result is too large to be represented in a variable

Prof. Shahzeb Malik


Operators are the symbols that are used to perform different operations on data.

Types of Operators +, -, * , / , and %


• Arithmetic Operators
>, <, ==, >=, <=, and !=
• Relational Operators
• Logical Operators &&, || and !
• Assignment Operators
=
• Increment and Decrement Operators
• Compound Assignment Operators ++, - -
+=, -=, *= , /= and %=

Prof. Shahzeb Malik


A statement that evaluates to a value is called an expression.
• Gives a single value
• Consists of operator and operand
Examples
A + B;
m / n;
x + 100;
+ is the operator
A and B are variables used as operands

Prof. Shahzeb Malik


Unary Operators
A type of operator that works with one operand is called unary operator.
• unary operators are –, ++, – –, !
• The above operators are used with one operand
a;
N++; Ternary Operators
The operators that operates on
– –x; three Operands.
Binary Operators
works with two operands is called binary operator.
• Some binary operators are +, –, *, /, %, >, && (AND), || (OR)
• The above operators are used with two operands
a + b;
x / y;
a > b;

Prof. Shahzeb Malik


Arithmetic operator is a symbol that performs mathematical operation on data.

Operation Symbol Description

Addition + Adds two values

Subtraction – Subtracts one value from another value

Multiplication * Multiplies two values

Division / Divides one value by another value

Modulus % Gives the remainder of division of two integers

Prof. Shahzeb Malik


• Also called remainder operator
• modulus operator (%) works only with integer values
• Computes the remainder resulting from integer division
7%5→2 12 % 3 → 0
3%5→3 3is not divisible by 5. Its result is 3

Prof. Shahzeb Malik


• C division operator (/)performs integer division if both operands are integers
• fractional part of the quotient is truncated
Examples
The result of 7 / 4 evaluates to 1 and 17 / 5 evaluates to 3
• If either operand is floating-point, the result is floating-point
Examples
The result of 7.0/2.0 is 3.5 and 13 / 5.0 is 2.6
5.0 / 2 → 2.5 4.0 / 2.0 → 2.0 17.0 / 5.0 → 3.4

Prof. Shahzeb Malik


Consists of constants, variables and arithmetic operators is called arithmetic expression.

Examples
Suppose we have two variables A and B where A = 10 and B = 5.

Arithmetic Expression Result


A+B 15
A–B 5
A*B 50
A/B 2
A%B 0

Prof. Shahzeb Malik


• An expression in which operands are of different data types is called mixed-type expression.

• The answer will be in big data type.


A statement that assigns a value to a variable is known as assignment statement.

Syntax

Assignment operator

variable = expression;

Examples
A = 100; A constant, variable or combination of
C = A + B; operands and arithmetical operators
X = C – D + 10;
• An lvalue is an operand that can be written on the left side of assignment operator =
• An rvalue is an operand that can be written on the right side of assignment operator =
• Lvalues must be variables
• rvalues can be any expression
Example
• distance = rate * time;
lvalue: "distance"
rvalue: "rate * time"
• All lvalues can be used as rvalues but all rvalues cannot be used as lvalues
• x = 5 is valid but 5 = x is not valid.
• C = A + B is valid but A+B=C is invalid.
• Compound assignment operators combine assignment operator with arithmetic operators

Syntax
Can be arithmetic operator
variable op = expression;
Example

Opera Example Equivalent to


tor
+= A += 10 A = A + 10
-= A -= 10 A = A - 10
*= A *= 10 A = A * 10
/= A /= 10 A = A / 10
%= A %= 10 A = A % 10
• ++ is a unary operator.
• increase the value of variable by 1.
A++; is equivalent to A = A + 1;

Prefix and Postfix Increments


• No difference if ‘alone’ in statement:
• A++; and ++A; → identical result
• Result of two statements x=a++ and x=++a are different

If ++ is after the variable, as in


a++, the increment takes place
after the expression is
evaluated
• Used to decrease the value of variable by 1
A--; is equivalent to A = A – 1;

Prefix and Postfix Decrements


• No difference if ‘alone’ in statement: A--; and --A; → identical result
Example Result of two statements x = a-- and x = --a are different.

If - - is after the variable, as in a- -, the


increment takes place after the
expression is evaluated
• Used to specify conditions in programs
• Either false (represented by 0) or true (represented by 1). e.g., “grade > 60” is a condition.
• Note: any non-zero digit represent true
• Also called comparison operators
A type of expression that consists of constants, variables and relational operators.
Number > 50
• The result of a relational expression can be true or false
Examples
Suppose the value of A = 10 and the value of B = 5.

Relation Expression Result


A>B True Relational
A<B False Variable operator Constant
A <= B False
A >= B True
A == B False
A != B True
A type of comparison in which more than one conditions are evaluated is called compound condition

Relational Operator

(Number > 50 && Number < 100)

Logical Operator Relational Operator


The logical operators are used to evaluate compound conditions.
• Types of logical operators
&& and
|| or
! not
AND Operator (&&)
• Produces true result if both conditions are true
• produces false result if any one condition is false
Example
Two variables A = 100 and B = 50
• Compound condition (A>10) && (B>10) is true
(5 && 9)
• Compound condition (A>50) && (B>50) is false
Result? T or F
AND Operator (| |)

• Produces true result if either conditions is true


• Produces false result if both conditions are false
Example
Two variables A = 100 and B = 50
• Compound condition (A>10) | | (B>10) is true
• Compound condition (A>50) | | (B>50) is true
• Compound condition (A>200) | | (B >100) is false
NOT Operator (!)
• Reverse the result of a condition
• Produces true result if conditions is false
•Produces false result if condition is true
Example
Two variables A = 100 and B = 50
Result of condition (A==B) is false but NOT operator converts it into true
• Condition !(A==B) is true.
• Condition !(A>B) is false.
Result of condition (A>B) is true but NOT operator converts it into false
The order in which different types of operators in an expression are evaluated.
• also known as hierarchy of operators
• Any expression given in parentheses is evaluated first
Example
Operator precedence Operator associativity

* and / have equal


precedence. These
expressions will be
evaluated from left to right.
Similarly, + and - also have
equal precedence.
• Non executable statements / ignored by the compiler.
• Make programs easy to read and modify
1. Sing-line Comments
2. Multi-line Comments

Prof. Shahzeb Malik


• Begin with // and continue to the end of line.

// Program 2.5: Finding the area of rectangle


int length = 12; // length in inches
int width = 15; // width in inches
int area; // calculated area

// Calculate rectangle area


area = length * width;

Prof. Shahzeb Malik


• Begin with /* and end with */
• Can span multiple lines.
/* Program 2.7
Description: Finding the area of circle
Written by: Abdullah */

• Can also be used as single-line comments.


int area; /* Calculated area */

Prof. Shahzeb Malik


Example
int x=20;
• Changing data types of value during program char y=‘a’
execution // y implicitly converted to int. ASCII
• Two types of casting: // value of 'a' is 97

1. Implicit Type Casting x = x + y;


printf(“x= %d” , x);
• Performed automatically by the C++ compiler
• If the data types of operands are different, the value Example
with lower data type is converted into higher data double
type.
x=3.6; int
2. Explicit Type Casting sum;
• Explicit casting is performed by programmer // Explicit conversion from double to
Syntax int sum = (int) x + 1;
(type) expression;
printf("sum = %d", sum);

Prof. Shahzeb Malik


Prof. Shahzeb Malik

You might also like