You are on page 1of 10

Workshop 3

Expressions

• Program is a set of statements executed sequentially.


• Statements are made out of expressions.
• Anything that evaluates to a numerical value is call an expression.
• Expressions are made out of one or more of
– constants
– variables
combined by using
– operators
• Expressions are the basic building blocks of a program.
• Examples for expressions

Expression Type
3 Constant
0x04A Constant
myAge Variable
x Variable
3+87 Constants combined via operator
x + 48.09 Constant and variable combined via operator
(5.0/9.0) * (tFar -32.0) Constant and variable combined via operator

3.1 Constants
The C has two types of constants.
• Literal Constants
• Symbolic Constants

3.1.1 Literal Constants


A literal constant is a value that is typed directly into the source code.
E.g. int count = 20;, float tax_rate=0.28;.
where, the 20 and 0.28 are literal constants.

Literal Constant Meaning


1.23 1.23
0.019 0.019
100. 100.0
1.23E2 123
1.23e2 123
1.23e-2 0.0123
1.23e2 123
0123 83, A constant starting with zero is treated as a octal integer
0x123 0X123 291, A constant starting with zero ans x or X is treated as a hex-
adecimal constant
1
3.1.2 Symbolic Constants
A symbolic constant is a constant that is represented by a name (symbol) in the program.
• First, symbolic constants to be used should be defined as
#define SYMBCONST symbconstvalue
then it can be used instead of the constant. This can make the code easier to understand (see the example
in Listing 3.1.
• A symbolic constant can also be defined by using the keyword const as a modifier applied to any variable
declaration A variable declared to be const can not modified during program execution - only initialized
at the time of declaration.
const int count = 100;
const float pi = 3.14159;
const long debt = 12000000;

Listing 3.1: Use of constants

# include < stdio .h >


columns
columns co
columns
columns co
columns
columns
# define RESISTANCE 86.45 co
columns
columns co
columns
columns
int main ( void ) co
columns
columns
{ float voltage ; co
columns const float current =7.23;
columns co
columns
columns co
voltage = current * RESISTANCE ;
columns
columns co
columns
columns co
columns
columns
return 0; co
columns
columns
} co

3.2 Variables
A variable is a named data storage location in computer’s Random Access Memory (RAM).
• To have a variable in C programming language, first it must be declared.
• The general form for variable declaration is
typename varname;
• Eg. In the Listing 3.2, a variable named x of type int has been declared by int x;.
• The keyword int defines the type of to be integer
– that is, the x can contain an whole number (not fractional numbers)
– 4 bytes are allocated for int type variables
– and therefore the values that can be assigned to x is limited to the range -2,147,483,648 to -
2,147,483,647
• The name of the variable x is then used in the program to access the variable. Examples
– x=1; the x is assigned the value 1.
– x=x+6; the 6 is added to x and the result (7) is then assigned back to x.
– y=x; the y is assigned the value of x
• C’s numeric variable types are summarized in Table 3.1
• Integer variables hold values that have no fractional part (i.e. whole numbers). Integer numbers come in
two flavors:
– signed integer variables can hold positive or negative values, whereas
– unsigned integer variables can hold only positive values (and zero).
• Floating-point variables hold values that have a fractional part (i.e. real Numbers)
2
Listing 3.2: Declaring and using a variable

columns
columns
# include < stdio .h > co
columns
columns co
int main ( void )
columns
columns co
columns
columns
{ int x ; /* declaration : int type variable x */ co
int y ; /* declaration : int type variable y */
columns
columns co
columns
columns co
x = 1;
columns
columns /* write : Assign 1 to x */ co
columns
columns
x = x + 6; /* Assigne x +6 to x */ co
columns
columns
y = x; /* read : from variable x and write to y */ co
columns
columns co
columns
columns
return 0; co
}
columns
columns co

Table 3.1: C’s Numerical Data Types in a 32-bit Compute

Variable Types Keyword Bytes Range


Re-
quired
Character char 1 -128 to 127
Integer int 4 -2,147,483,648 to -2,147,483,647
Short Integer short 2 -32768 to 32767
Long Integer long 8 -2,147,483,648 to -2,147,483,647

Unsigned Character unsigned char 1 0 to 255


Unsigned Integer unsigned int 4 0 to 4,294,967,295
Unsigned Short In- unsigned short 2 0 to 65535
teger
Unsigned Long In- unsigned long 8 0 to 4,294,967,295
teger

Single Precision float 4 1.2e−38 to 3.4e38


Floating Point
Double Precision double 8 2.2e−308 to 1.8e308
Floating Point

3.2.1 Use of scanf() and printf() with Variables


scanf()
• The following example shows how to use scanf() to read an integer value from keyboard and store it in
a int type variable x.

scanf("%d", &x);

where,
– &x is the address of x
– "%d" indicates that the user input characters must be formatted as an integer (specified by the letter
d) and then store in x.
– The letter d is one of the format specifiers in C

Table 3.2: C Keywords

asm auto break case char const continue default


do double else enum extern float for goto
if int long register return short signed sizeof
static struct switch typedef union unsigned void volatile
while
3
– Format specifier should match with the type of the variable (x)
– The list of format specifies is listed in Table 3.3.
– How to read some of other input types are given in the Listing 3.3.

printf()
• The following example shows how to use printf() to write an integer stored in int type variable x on
the Terminal.

printf("%d", x);
where,
– printf() prints characters of the text string given within " and ".
– However, in place of the format specifier \%d, it prints the value of the variable given after the ,
(that is value of x) after formating it as indicated by the format specifier (that is as an integer)
– The letter d is one of the format specifiers in C
– Format specifier should match with the type of the variable (x)
– The list of format specifies is listed in Table 3.3.
– How to print some of other variable types are given in the Listing 3.3.
the

3.3 Variable Selection


Variable names
Variable names are subjected to following rules.
• The names can contain letters, digits, and underscore character.
• The first character of the name must be a letter. Underscore is also legal though is not recommended to
use.
• Case matters (i.e. upper and lower case letters). C is case sensitive, thus, the names count and
Count refer to two different variables.
• C keywords (see Table 3.2 for the complete list) can not be used as variable names. A keyword is a word
that is part of the C language.
• For many compilers, a C variable name can be up to 31 characters long.
• It is recommended to create variable names that reflect the meaning of data being stored. For example,
interest_rate, Interest_Rate, intrestRate, accFixed, accSavings, accCurrent

Variable Type
The variable type selected in your program must match with the
• type of information that you intended to store (integer , fractional numbers, character, string, ..)
• expected range of values (maximum and minimum) that might store in the variable.

3.4 Operators
• An operator is a symbol that instructs C to perform some operation, or action on one or more operands.
• An operand is something that an operator acts on.
• In C, all operands are expressions.
• C operators fall into several categories.
– The assignment operator
– Mathematical operators
– Relational operators
– Logical operators
4
Table 3.3: C’s format specifiers

Format Specifier Description Supported Data Types


%c Character char, unsigned char
%d or %i Signed Integer short, unsigned short, int, long
%f Floating Point float
%e or %E Scientific Notation of float, double
float values
%i Signed Integers int, long, short, unsigned short int, long
%l or %ld or %li Signed Integer long
%lf Floating Point double
%Lf Floating Point long double
%lu Unsigned Integer unsigned int, unsigned long
%lli or %lld Signed Integer long long
%llu Unsigned Integer unsigned long long
%o Octal representation of short, unsigned short, int, unsigned int, long
Integers
%p Address of pointer to void *
void *
%s String char *
%u Unsigned Integer unsigned int, long
%x or %X Hexadecimal representa- short, unsigned short, int, unsigned int, long
tion of Unsigned Integer
%% Prints character %

3.4.1 The Assignment Operator =


• Has the format:
variable = expression .
• Assignment operator evaluates the left side expression (left side operand) and assigns the result to right
side variable (right side operand).
Eg. x=y means “assign the value of y to x”.
• Chaining is possible i.e. x=y=z;

3.4.2 The Mathematical Operators


The C has two anary operators (take a single operand);
++, --
and five binary mathematical operators (take two operands);
+, -, *, /, %.

Anary Mathematical Operators


• ++x; same as x=x+1;

• --x; same as x=x-1;


• Can be placed
– before its operand (prefix mode), or
(operators modify their operands before it’s use)
x=10; y=++x;
After these statements, each x and y has the value 11
– or after its operand (postfix mode)
(operators modify their operands after it’s use) x=10; y=x++;
After these statements, x has the value 11 and y has the value 10

Briefly: ++i adds one to the stored value of i and ”returns” the new, incremented value to the surrounding
expression; i++ adds one to i but returns the prior, unincremented value.

5
Binary Mathematical Operators
• Usage of main operators +, -, *, /, %. must be clear!
• See the Listing 3.4 for exemplary usage of % operator

3.4.3 The Relational Operators


• C relational operators are used to compare expressions, asking questions such as ”Is x greater than 100?”
or ”Is y is equal to 0?”.
• An expression containing a relational operator evaluates to either true or false having numerical values 1
or 0, respectively.
• Evaluate:
5==1 5>1 5 !=1 (5+10) ==(3*5)
x = (5==5) x =1 x =(5!=5) x = 0
x = (12==12) + (5!=3) x = 2

3.4.4 The Logical Operators


• C’s logical operators allows to combine two or more relational expressions into a single expression that
evaluates to either true or false.
Eg. ”If it’s 7.00am and a weekday and not my vacation, ring the alarm”
• exp1 && exp2 true if only if both exp1 and exp2 are true; false otherwise.
• exp1 || exp2 true if either exp1 or exp2 is true; false only if both are false.
• !exp1 false if exp1 is true if exp1 is false.
• E.g. (5==5) && (6!=2), (5>5) && (6<1), (2==1) && (5==5), (5==4)

Note on True/False Values


• C’s relational expressions are evaluate to 0 to represent false and to 1 to represent true.
• Any numerical value is interpreted as either true or false when it is used in a C expression or statement
that is expecting a logical value. The rules for this are as follows.
– A value of zero represents false.
– Any nonzero value represents true.
• E.g. if(x=5) printf("%d",x);
(expression) is equivalent to (expression!=0)
(!expression) is equivalent to (expression==0)

3.4.5 Operator Precedence and Parentheses


In an expression that contains more than one operator, what is the order in which operations are performed?

• x = 4 + 5 *3
– if 4 + 5 evaluated first then y becomes 27.
– if 5 * 3 evaluated first then y becomes 19.
• See Table 3.5 for complete list of operator precedence.
• If an expression contains more than one operator with the same precedence level, the operators are
performed from left to right. E.g. y=12 % 5 * 2;, x = 4 + 5 *3
• C uses parentheses to modify the evaluation order. A sub-expression enclosed in parentheses is evaluated
first, without regard to operator precedence. E.g. x = (4 + 5) *3
• Multiple and nested parentheses are possible. Evaluation proceeds from the innermost parentheses on-
wards. E.g. y = 25 - (2 * (10 + (8/2)));
• Do use parentheses to make the order of expression evaluation clear.

6
Table 3.4: C Operators
Operator Symbol Action Examples
Assignment = Left side expression is evaluated and re- x=y;
sulting value is assigned to right side vari-
able
Increment ++ Increments the operand by one ++x, x++
Decrement -- Decrements the operand by one --x, x--
Addition + Adds two operands x+y
Subtraction - Subtracts the left operand from the right x-y
operand

Multiplication * Multiplies two operands x*y


Division / Divides the right operand from the left x/y
operand

Modulus % Gives the reminder when the right x%y


operand is divided by the left operand

Equal == Is left operand equal to right operand? x==y

Greater than > Is left operand greater than right x>y


operand?

Less than < Is left operand less than right operand? x<y

Greater than or >= Is left operand greater than or equal to x>=y


equal to right operand?

Less than or <= Is left operand less than or equal to right x<=y
equal to operand?

Not equal != Is left operand not equal to right operand? x!=y

Logical AND && Logical AND between operands (expres- exp1 && exp2
sions)

Logical OR || Logical OR between operands (expres- exp1 || exp2


sions)

Logical NOT ! Logical NOT between operands (expres- !exp1


sions)

+= Add right side operand to left side x+=y


operand and assign result to left side
operand
-= Subtract left side operand from right side x-=y
operand and assign result to left side
operand
*= Multiply left side operand and right side x*=y
operand and assign result to left side
operand
/= Divide left side operand by right side x/=y
operand and assign result to left side
operand
%= Modulus left side operand and by side x/=y
operand and assign result to left side
operand
Bitwise Logical & Operands are logical AND in bitwise x & y
AND

7
Bitwise Logical | Operands are logical OR in bitwise x | y
OR
Bitwise Logical ^ Operands are logical XOR in bitwise x ^ y
XOR
Bitwise Logical ~ Operand is logical NOT in bitwise ^x
Complement

Table 3.5: C operator precedence


Level Operators
1 () (function operator ), [] (array operator ) -¿ .
2 ! ~ ++ -- * (indirection), & (address of ) (Type) sizeof + - unary
3 * (multiplication) / %
4 + -
5 << >>
6 < <= > >=
7 == !=
8 & (bitwise AND)
9 ^
10 |
11 &&
12 ||
13 ?:
14 = += .= *= /= %= &= ^= |= <<= >>=
15 ,

8
Listing 3.3: Use of scanf() and printf() with some variable types

columns
columns
/* scanf () and printf () with some variable types co
*/
columns
columns co
columns
columns
# include < stdio .h > co
columns
columns co
int main ( void )
columns
columns co
columns
columns
{ co
unsigned char mGender ;
columns
columns co
columns
columns
int mAge ; co
float mMarksGeo , mMarksMth ;
columns
columns co
columns
columns
double mWeight , mHeight ; co
columns
columns co
columns
columns
printf ( " What is your gender ( M / F ) : " ) ; co
columns
columns
scanf ( " % c " ,& mGender ) ; co
columns
columns co
columns
columns
printf ( " \ nWhat is your age ( in years ) : " ) ; co
scanf ( " % d " ,& mAge ) ;
columns
columns co
columns
columns co
columns
columns
printf ( " \ nWhat is your marks for Mathematics (0 -100) : " ) ; co
columns
columns
scanf ( " % f " ,& mMarksMth ) ; co
columns
columns co
columns
columns
printf ( " \ nWhat is your marks for Geography (0 -100) : " ) ; co
columns
columns
scanf ( " % f " ,& mMarksGeo ) ; co
columns
columns co
columns
columns
printf ( " \ nWhat is your Weight ( in kg ) : " ) ; co
columns
columns
scanf ( " % lf " ,& mWeight ) ; co
columns
columns co
columns
columns
printf ( " \ ntWhat is your Height ( in m ) : " ) ; co
columns
columns
scanf ( " % lf " ,& mHeight ) ; co
columns
columns co
columns
columns
printf ( " \n - - - - - - - - - - - - - " ) ; co
columns
columns
printf ( " \n - Your Info -" ) ; co
columns
columns
printf ( " \n - - - - - - - - - - - - - " ) ; co
columns
columns co
columns
columns
printf ( " \ n Gender = % c \ t Age : % d " , mGender , mAge ) ; co
printf ( " \ n Marks for Geography = % f and for Mathamatics = % f " ,
columns
columns co
columns
columns
mMarksGeo , mMarksMth ) ; co
columns
columns
printf ( " \ n Avarage Marks = % f " , ( mMarksGeo + mMarksMth ) /2.0) ; co
columns
columns
printf ( " \ n Weight = % lf , Height = % lf " , mWeight , mHeight ) ; co
columns
columns
printf ( " \ n Ratio Weight / Height = % lf " , mWeight / mHeight ) ; co
columns
columns co
columns
columns co
return 0;
columns
columns co
columns
columns
} co

9
Listing 3.4: Demonstrating the modulus operator

/* Illustrates the modulus operator */


columns
columns co
columns
columns
/* Inputs a number of seconds , and */ co
/* converts to hours , minutes and seconds */
columns
columns co
columns
columns
# include < stdio .h > co
columns
columns co
/* Define constants */
columns
columns co
columns
columns
# define SECS_PER_MIN 60 co
# define SECS_PER_HOUR 3600
columns
columns co
columns
columns co
columns
columns
unsigned int seconds , minutes , hours , secs_left , mins_left ; co
columns
columns co
columns
columns co
columns
columns
int main ( void ) co
columns
columns
{ /* Input the number of seconds */ co
columns
columns co
columns
columns
printf ( " Enter the number of seconds ( <65000) : " ) ; co
columns
columns
scanf ( " % d " , seconds ) ; co
columns
columns co
columns
columns
hours = seconds / SECS_PER_HOUR ; co
columns
columns
minutes = seconds / MINS_PER_HOUR ; co
columns
columns
mins_left = minutes % SECS_PER_MIN ; co
columns
columns
secs_left = seconds % SECS_PER_MIN ; co
columns
columns co
columns
columns
printf ( " % u seconds is equal to " , seconds ) ; co
columns
columns
printf ( " % u h , % u m , and % u s \ n " , hours , mins_left , secs_left ) ; co
columns
columns co
}
columns
columns co

10

You might also like