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

computer methods c programming

Lecture 4 covers expressions and assignments in C programming, detailing variable types, declarations, enumerative types, and the use of typedef for defining new types. It explains constants, named constants, order of evaluation, precedence, and associativity of operators, as well as type conversions and assignment operations. The lecture concludes with examples and exercises to reinforce the concepts discussed.

Uploaded by

Thabiso Kyle
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 views21 pages

computer methods c programming

Lecture 4 covers expressions and assignments in C programming, detailing variable types, declarations, enumerative types, and the use of typedef for defining new types. It explains constants, named constants, order of evaluation, precedence, and associativity of operators, as well as type conversions and assignment operations. The lecture concludes with examples and exercises to reinforce the concepts discussed.

Uploaded by

Thabiso Kyle
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/ 21

COMPUTER METHODS 1

LECTURE 4

Expressions and Assignments

1 / 21 Lecture 4: Expressions and Assignments Computer Methods 1


Types

Each variable and constant in an expression possesses a type which is


specified when the variable is declared or by the construction of the
constant. The type indicates what range of values a variable is able to
hold together with how much memory is needed to store it.
C provides four basic types char, int, float , and double
The qualifiers signed or unsigned can be applied to char and int, the
qualifiers short or long to int and long to double.
This gives rise to the eleven following types:
Type Alternatives
char
signed char
unsigned char
short signed short, short int, signed short int
int signed, signed int
unsigned unsigned int
long signed long long int, signed long int
unsigned long unsigned long int
float
double
long double

2 / 21 Lecture 4: Expressions and Assignments Computer Methods 1


Declarations of Variables

Each variable needs to be declared before it can be used. The


form of declaration is:
type identifier1, identifier2, ...;
This enables us to declare one or more variables to be of the
same type.
Example: the following are possible declarations:
char aLetter;
int aNumber;
long aBigNumber, anotherBigNumber;
unsigned long positiveBigNumber;
long double averyLargeNumber;
signed short int aLittleOne;

3 / 21 Lecture 4: Expressions and Assignments Computer Methods 1


Enumerative Type
Some applications require variables which are able to take only a limited range
of values. For instance, in a program concerned with playing cards, we may need
to represent the suit of a card. The natural values are club, diamond, heart and
spade
Without any special language facility, we might choose integer values to stand
for these. Any values will do since they are to be used only as indicators. Let us
use 0,1,2 and 3. The program could then contain :
int card;
...
card =2;

This is a poor handle of the situation since we need to remember what the value
2 stands for.
An improvement could be achieved by using the pre-processor to give names to
the values:
#define club 0
#define diamond 1
#define heart 2
#define spade 3
int card;
...
card = heart;

4 / 21 Lecture 4: Expressions and Assignments Computer Methods 1


Enumerative Type(cont’d)

Another improvement could be achieved by using constant integers:


const int club 0;
const int diamond 1;
const int heart 2;
const int spade 3;
int card;
...
card = heart;

5 / 21 Lecture 4: Expressions and Assignments Computer Methods 1


Enumerative Type(cont’d)

C offers a more compact way of achieving the same effect. The enumeration
type enables us to set the values which a variable may take without the need for
many #define directives
enum suit {club, diamond, heart, spade};

Which defines a new type enum suit together with the values it may take; We
may then declare variables of type:
enum suit card;

It means the type is enum suit and the variable is card.


It is then possible to have the following fragment of code
card = heart;
...
if(card == spade) ...;

This is not a completely new type; it is simply another representation of the


type int. The identifiers club, heart, diamond, and spade are given the values 0,
1, 2 and 3.

6 / 21 Lecture 4: Expressions and Assignments Computer Methods 1


Defining New Types -typedef
There are times when it is convenient to define a new type, specific to a
particular program. But, really C does not provide facility to create new
types but simply means of giving new names to existing types. By
preceding a normal declaration by the keyword typedef, the identifier
becomes an alternative name for the type instead of being a variable.
Example:
typedef float velocity;
typedef int counter;
typedef enum {false, true} boolean;
typedef enum {club, diamond, heart, spade} suit;
We can then have the following situations:
The identifier velocity is now an alternate name of the type
float and can be used as follows:
velocity startingSpeed, maxSpeed;
Similarly we can have the following declarations:
counter index;
suit card;
boolean flag, ok;

7 / 21 Lecture 4: Expressions and Assignments Computer Methods 1


Constants
The type of a constant is determined by the way in which it is written.
Some example are the follwing:
integer constants : 3, 345, -78, 345566, 0
double constants : 1.2, -0.45, 34556.667, -64.6e-4
character constants : ’a’, ’A’, ’3’, ’>’
string constants :"Hello World", "Computer Engineering", "Justice"

Some useful characters do not have a printable form, to overcome this


problem the following are legal
’\a’ alert - visible or audible
’\b’ backspace
’\f’ form feed
’\n’ newline
’\r’ carriage return
’\t’ horizontal tab
’\v’ vertical tab
’\’’ single quote
’\"’ double quote
’\?’ question mark
’\\’ backslash

8 / 21 Lecture 4: Expressions and Assignments Computer Methods 1


Named constants

It is often considered a good programming practice to give meaningful names to


constants. The declaration of a named constant can have the following two
syntaxes:
1 const type identifier = aValue;
2 #define identifier aValue
Exercise 3.1:
/* ******************************************************************
* cm18_3_1.c -- This program to calculate the surface of a circle *
********************************************************************/
#include <stdio.h>
const float PI = 3.141592;
int main()
{ float R, Surface;

printf("Please enter the radius of the circle:");


scanf("%f", &R);
Surface = R*R*PI;
printf("\nThe Surface of Circle of radius %8.2f is %8.2f",R,Surface);
return 0;
}

9 / 21 Lecture 4: Expressions and Assignments Computer Methods 1


Exercise 3.2

Using #define directive to define PI used in the formula to


compute the volume, V, of a sphere of radius r (V = 34 πr 3 ).
/* ******************************************************************
* cm18_3_2.c -- This program to calculate the volume of a sphere *
********************************************************************/
#include <stdio.h>
#define PI 3.141592
int main()
{ float radius, Volume;

printf("Please enter the radius of the sphere:");


scanf("%f", &radius);
Volume = (4.0/3.0)*radius*radius*radius*PI;
printf("\nThe volume of a sphere of radius %8.2f is %8.2f",radius,Volume);
return 0;
}

10 / 21 Lecture 4: Expressions and Assignments Computer Methods 1


Order of Evaluation

Expressions are constructed from constants and variables combined together by


operators:
binary operators : +, ∗, /, <, − . . .
unary operators : !, −, . . .
Ternary operator: ?:
When an expression contains 2 or more operators it is necessary to understand
the order in which the operations are carried out. For instance, we would expect
all the following to have the same effect and ultimate value:
Example 1:
one*two + three/four
(one*two) + three/four /* unnecessary parentheses */
one*two + (three/four) /* unnecessary parentheses */
(one*two) + (three/four) /* unnecessary parentheses */

whereas the following would have a different meaning and effect:


Example 2:
one*(two + three)/four

11 / 21 Lecture 4: Expressions and Assignments Computer Methods 1


Order of Evaluation: precedence and associativity

Two concepts are important to be able to understand and construct


expressions: precedence and associativity of operators. The table in the
next slide sets out all the C operators in groups with the highest
precedence, namely the postfix, at the top and that with the lowest
precedence, namely the sequence at the bottom. The associativity within
each group is shown to the right of the table.
In example 1 we would naturally expect the multiplication (*) and
division (/) will be carried out before the addition(+). In fact, what
happens is that the table shows that the multiplicative operators have a
higher precedence than the additive operators.
The order of precedence can always be changed by the use of parentheses
as example 2 shows.

12 / 21 Lecture 4: Expressions and Assignments Computer Methods 1


Evaluation of Expressions

The table below defines the rules for evaluating expressions


1. Parentheses Evaluate parenthesized subexpressions first

2. Precedence Evaluate operators according to this precedence:


(i) unary + unary -
(ii) * / %
(iii) binary + binary -

3. Associativity If there is a sequence of two or more operators


of same precedence, evaluate unary operators
right to left (right associativity) and binary
and binary operators left to right (left asso-
ciativity).

Operators / and %
When applied to integer operands, the operators / and % calculate the integer
quotient and remainder, respectively.
38 / 7 = 5 and 38 % 7 = 3

13 / 21 Lecture 4: Expressions and Assignments Computer Methods 1


Order of Evaluation: precedence and associativity(cont’d)

Group Operator Associativity


postfix () [] , − > left to right
unary ! ~ ++ - - + * & (type) sizeof right to left
multiplicative */% left to right
additive +- left to right
shifting >> << left to right
relational < > >= <= left to right
equality != == left to right
bitwise and & left to right
bitwise complement ^ left to right
bitwise or | left to right
logical and && left to right
logical or || left to right
conditional ?: right to left
assignment = += -= *= /= %= &= ^= |= <<= >>= right to left
sequence , left to right

14 / 21 Lecture 4: Expressions and Assignments Computer Methods 1


precedence and associativity: Example

a b a/b (a/b)*b a%b (a/b)*b+a%b


13 5 2 10 3 13
-13 5 -2 -10 -3 -13
13 -5 -2 10 3 13
-13 -5 2 -10 -3 -13

15 / 21 Lecture 4: Expressions and Assignments Computer Methods 1


Step by step Evaluation of p/-q+(r-s+t)*n

n p q r s t
10.0 4.8 -2.0 8.5 12.0 0.5

p / -q + (r - s + t) * n
----- Within parentheses,
-3.5 - and + are of the
-------- same precedence:
-3.0 apply left associativity
---
2.0 Unary operators have highest
-------- precedence / and
2.4 * have same precedence
-------------- Apply left associativity.
-30 + has lowest precedence
--------------------------
-27.6

16 / 21 Lecture 4: Expressions and Assignments Computer Methods 1


Type conversions
All integer arithmetic is performed with at least the range of
an int. As a consequence, a character or short integer
appearing in an expression is first converted to int. This
process is called integral promotion.
The promotion of operands of type char to type int means
that it is sensible to perform arithmetic operations on data of
type char. From the ASCII character set ’D’ is represented by
68;’A’ by 65; ’z’ by 122 and ’a’ by 97 thus:
’D’ - ’A’ evaluates to : 68 - 65 = 3
’z’ -’a’ +1 evaluates to 122 -97 +1 = 26
If ch is a variable of type char and currently represents any
upper case letter in the ASCII character set, then the
expression:
ch -’A’+’a’
evaluates to the integer value with the ASCII code that
represents the equivalent lower case letter.
17 / 21 Lecture 4: Expressions and Assignments Computer Methods 1
Assignment

The assignment operator allows the assignment of some value


to a program variable
The simplest form of the assignment operator is:
variable = expression

The effect of the operator is to evaluate the expression to the


right of the assignment operator (=) and the resulting value is
then assigned to the variable on the left.

18 / 21 Lecture 4: Expressions and Assignments Computer Methods 1


Type cast operator

In addition to implicit type conversion which can occur across


the assignment operator and in mixed expression, there is an
explicit type conversion called cast . If the variable date is an
int then:
(double) date

will cast or coerce the value of date so that the expression


has the type double
A cast expression consists of a left parenthesis, a
type-specifier, a right parenthesis and an operand expression
(type-specifier) expression

We will have the following:


float PseudoIntNumber = (int)(12,5/2,0); PseudoIntNumber will hold 6
float FloatNumber = (float) 13/(float) 2; FloatNumber will hold 6.5

19 / 21 Lecture 4: Expressions and Assignments Computer Methods 1


Example(cont’d)

/***************************************************
* cm18_3_3.c -- Casting *
***************************************************/
#include <stdio.h>
int main()
{
float PseudoIntNumber = (int)(12.5/2.0);
float FloatNumber = (float) 13/(float) 2;
printf("\nPseudoIntNumber holds %f ", PseudoIntNumber );
printf("\nFloatNumber holds %f ", FloatNumber );
return 0;
}

20 / 21 Lecture 4: Expressions and Assignments Computer Methods 1


Your To Do work

1 Read your lecture 4


2 Complete Practical 3

21 / 21 Lecture 4: Expressions and Assignments Computer Methods 1

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy