C Programming
Variables and Operations
A. Sahu amd S. V .Rao
Dept of Comp. Sc. & Engg.
Indian Institute of Technology Guwahati
1
Outline
• C Statements and Block of Statement
• Comments in C
• Operators in C
• B‐E‐DM‐AS Rule
• E
Examples
l : Basic
B i operations
ti
• Program examples
• Good Programming practice
2
Variables in C (quick recap)
• Variables are
– Named blocks of memory
– Valid identifier.
• Variable have two properties in syntax:
– Name — a unique identifier
– Type
y — what kind of value is stored.
• It is identifier, that
– Value may change during the program execution.
• Every variable stored in the computer’s
memory
– Has a name, a value and a type.
Variable Naming Conventions
(quick recap)
• C programmers generally agree on the
following conventions for naming
variables.
– Begin variable names with lowercase letters
– Use meaningful
g identifiers
– Separate “words” within identifiers with
underscores or mixed upper and lower case.
case
– Examples: surfaceArea,
surface Area surface_area
surface_Area, surface area
– Be consistent!
Numeric Data Type (quick recap)
• char, short, int, long int
– char : 8 bit number (1 byte=1B)
– short: 16 bit number (2 byte)
– int : 32 bit number (4B)
– long int : 64 bit number (8B)
• float, double, long double
– float : 32 bit number (4B)
– double : 64 bit number (8B)
– long double : 128 bit number (16B)
5
Numeric Data Type (quick recap)
unsigned char
char
g
unsigned short
short
Unsigned int
int
6
Testing size of Numeric Data
#include<stdio.h>
int main(){
printf("size
i f(" i off char
h %d\
%d\n",
" sizeof(char));
i f( h )) //1
printf("size of short %d\n",sizeof(short)); //2
printf("size
printf( size of int %d\n
%d\n",sizeof(int));
sizeof(int)); //4
printf("size of long int %d\n",sizeof(long int)); //8
printf("size of float \n",sizeof(float)); //4
printf("size of double %d\n",sizeof(double));//8
printf("size of long double %d\n",
sizeof(long double));//16
return 0;
} 7
Numeric Data Type (quick recap)
Numeric Data Type
Integral Fractional
char short int long int float double long
double
char short int long int
• char, short, int, long int
– Signed and unsigned
• float, double, long double 8
C Statements
• Statements are terminated with a
semicolon and that is ';'
• e.g:
e g:
char acharacter;
int i, j = 18, k = -20;
printf("Initially,
p y g given
j = 18 and k = -20\n");
C Programming : Sum of A and B
#include <stdio.h>
int
i t main(){
i (){
int A,B, S; Statement 1
printf(“Enter
printf( Enter two
numbers ”); Statement 2
scanf(“%d %d”,&A,&B);
Statement 3
S=A+B;
Statement 4
printf(“Res=%d”, S);
Statement 5
return 0;
} Statement 6 10
C: Block of Statements
G
Group off statements (compound
( d statement)) are
enclosed by curly braces: { and }.
Mark
M k the
th start
t t and
d the
th end
d off code
d block.
bl k
C Programming : Sum of A and B
#include <stdio.h>
Start of the BLOCK
int
i t main(){
i (){
int A,B, S; Statement 1
printf( Enter two
printf(“Enter
numbers ”); Statement 2
scanf(“%d %d”,&A,&B);
Statement 3
S=A+B;
Statement 4
printf(“Res=%d”, S);
Statement 5
return 0;
} Statement 6
End of the BLOCK 12
Comments in C
Single
Si l liline off comment:
t // comment here
More than single line of comment or
expanded: /* comment(s) here */
#include
#i l d <<stdio.h>
tdi h> // ffor printf()
i tf()
/* main() function, where program
execution starts */
int main(){
/* declares variable and
initializes it*/
it /
int i = 8;
printf(“value of i=%d\n”,i);
return
t 0
0;
}
Declaring Variables
• Before using a variable, you must give the
compiler some information about the
variable; i.e., you must declare it.
• The declaration statement includes the data
yp of the variable.
type
• Examples of variable declarations:
int length ;
float area ;
Declaring Variables
• When we declare a variable
– Space is set aside in memory to hold a value of the
specified data type
– That space is associated with the variable name
– That space is associated with a unique address
• Visualization
Vi li ti off th
the d
declaration
l ti
int length ; length
Garbage value
FE07
Using Variables: Initialization
• Variables may be be given initial values, or
initialized
initialized, when declared
declared. Examples:
length
int length=7;
length 7; 7
diameter
fl t di
float diameter=5.9;
t 5 9 59
5.9
initial
char initial =‘A’; ‘A’
Using Variables: Initialization
• Do not “hide”
hide the initialization
– Put initialized variables on a separate line
– A comment is always a good idea
– Example:
int height; g ; / /* rectangle g height
g */
/
int width=6; /* rectangle width */
int area; /* rectangle g area */
NOT int height, width = 6, area ;
Using Variables: Assignment
• Variables may have values assigned to them through the use
of an assignment statement.
– Uses the assignment operator =
• This operator (=) does not denote equality.
• It assigns the value of the righthand side of the statement (the
expression) to the variable on the lefthand side.
• Only single variables may appear on the lefthand side of the
assignment operator.
• Examples:
diameter = 5
di 5.9
9 ;
area = length * width ;
Using Variables: Assignment
• variable= <const|Expression>
• <Expresion> can be simple or complex expression
area = length
l th * width
idth ;
Arithmetic Operators in C
Name Operator Example
Addition
ddi i + num1 + num2 2
Subtraction ‐ initial ‐ spent
Multiplication * fathoms * 6
Division / sum / count
Modulus % m%n
Division
• Integer division
– If both operands of a division expression are
integers,
– you will get an integer answer.
• The fractional portion is thrown away.
• Examples : 17 / 5 = 3
4 / 3 = 1
35 / 9 = 3
Division : float
• Division
s o where
e e at least
east o
onee ope
operand
a d iss a floating
oat g
point number will produce a floating point
answer.
• Examples: 17.0 / 5 = 3.4
4 / 3.2 = 1.25
35.2 / 9.1 = 3.86813
• What happens? The integer operand is
temporarily converted to a floating point, then
the division is performed.
Division By Zero
• Division by zero is mathematically undefined
undefined.
• If you allow division by zero in a program, it
will cause a fatal error
error.
• Your program will terminate execution and
give
i an error message.
• Non‐fatal errors do not cause program
termination, just produce incorrect results.
Modulus
• The expression m % n yields the integer
remainder after m is divided by n.
• Modulus is an integer operation ‐‐ both
operands MUST be integers.
• Examples
E l : 17 % 5 = 2
6%3 = 0
9%2 = 1
5%8 = 5
Uses for Modulus
• Used to determine if an integer value is even
or odd
5 % 2 = 1 odd 4 % 2 = 0 even
If you take the modulus by 2 of an integer, a
result of 1 means the number is odd and a
result of 0 means the number is even
C Example 1: Area of Rectangle
Read the two sides of a
START
rectangle and calculate its
area. Input W, L
Area← L x W
• Step 1: Input W,L
Print Area
• Step 2: Area ← L x W
• Step 3: Print Area
STOP
C Example 1: Area of Rectangle
#include <stdio.h>
START
int main(){
Input W, L
int L,W,
L W Area;
printf(“Enter L & B ”);
scanf(“%d %d”,&L,&B); Area ← L x W
Area=L*B; Print Area
printf(“Area=%d”,Area);
return 0; STOP
}
C Example 2: Area of Circle
Read the radius of circle
START
and calculate its area.
Input r
• St
Step 1
1: Input
I tr Area ← PI x r x r
• Step 2:Area ← PI x r x r Print Area
• Step 3: Print Area
STOP
C Example 2: Area of Rectangle
#include <stdio h>
<stdio.h>
$define PI 3.142
int main(){
START
float rad, Area;
printf(“Enter radius”); Input W, L
scanf(“%f”,&r);
Area=PI*r*r; Area ← PI x r x
r
printf(“Area=%f”,Area);
p ( , ); Print Area
return 0;
}
STOP
The literal PI value get replaced by 3.142
$gcc –E arearect.c >Preproces.c
C Example 3: Temp Conversion
Read the temp in Celsius
START
and calculate temp in
Fahrenheit. Input Tc
Tf=(9/5)*Tc +32
Tf ← 1.8
1 8 x Tc + 32
• Step 1: Input Tc
Print Tf
• Step 2:Tf ←(1.8xTc) +32
• Step 3: Print Tf
STOP
C Example 3: Temp Conversion
#include <stdio.h>
START
int main(){
Input Tc
float Tc,Tf;
Tc Tf;
printf(“Enter Tc”);
scanf(“%f”,&Tc); Tf ← 1.8
1 8 x Tc + 32
Tf=(1.8*Tc)+32; Print Tf
printf(“Tf=%f”,Tf);
return 0; STOP
}
C Example 4: Force Between Two
b d
bodies
Read the masses m1 and
START
m2 of bodies, and dist
and calculate Force Input m1, m2, r
F=G*m1*m1 /r2
F ←G*m1*m1 //r2
• Step 1: Input m1, m2
Print F
• Step 2:F ←G*m1*m1 /r2
• Step 3: Print F
STOP
C Example 3: Temp Conversion
#include <stdio h>
<stdio.h>
int main(){
float
oat F,
, m1,m2,r;
, , ;
START
float G=6.673e-11;
printf(“Enter m1 m2”); Input m1, m2, r
scanf(“%f %f”,&m1,&m2);
printf(“Enter r”);
F ←G*m1*m1 //r2
scanf(“%f”,&r);
f(“%f” & )
F=(G*m1*m2)/(r*r);
F (G m1 m2)/(r r); Print F
printf(“Tf=%f”,F);
STOP
return 0;
}
Expression
p Evaluation
34
Algebra: BEDMAS/PEDMAS Rule
• B‐E‐DM‐AS or P‐E‐DM‐AS or B‐O‐DM‐AS
• B/P
/ : Bracket
k or Parenthesis
h ( )
– In C, only ( ) used for expression
– Curly braces {}, and square bracket [] used for
some other purpose.
• Again [] may involves in expression as in the form of
array access
• E : Exponentiation or Order (O)
• DM: Division and Multiplication
• AS : Addition and Subtraction
35
BEDMAS Example
• Evaluate 8+3*4/2
– DM have higher priority as compared to AS
– All DM get evaluated left to right
8+3*4/2 = 8+ 12/2 = 8+6 = 14
• Evaluate 15‐(6+1)+30/(3*2)
15‐(6+1)+30/(3*2)= 15‐(7)+30/(6)
15‐7+5=8+5=13
• Evaluate (95/19)2+3
– (95/19)2+3 = (5)2+3 = 25+3 =28
36
BEDMAS equivalent in C
Arithmetic Operators Precedence Rule
Operator(s) Precedence & Associativity
() Evaluated first. If nested
(embedded), innermost first.
* / % Evaluated second. If there are
several, evaluated left to right.
+ ‐ Evaluated third. If there are
several, evaluated left to right.
= Evaluated last, right to left.
Using Parentheses
• Use parentheses to change the order in which
an expression is evaluated.
a + b * c Would multiply b * c first,
tthen
e add a to the
t e result.
esu t
If you really want the sum of a and b to be
p
multiplied byy c,, use parentheses
p to force the
evaluation to be done in the order you want.
(a + b) * c
• Also use parentheses to clarify a complex
expression.
expression
Practice With Evaluating Expressions
Given integer variables a, b, c, d, and e,
where a = 1,
1 b = 2,
2 c = 3,
3 d = 4,
4
evaluate the following expressions:
a + b - c + d
a * b / c
1 + a * b % c
a + d % b - c
e = b = d + c / b - a
Practice With Evaluating Expressions
Given integer variables a, b, c, d, and e,
where a = 1,
1 b = 2,
2 c = 3,
3 d = 4,
4
evaluate the following expressions:
a + b - c + d =3-3+4=0+4=4
a * b / c = 2/3+4=0+4=4
2/3+4 0+4 4
1 + a * b % c =1+2%3=1+2=3
a + d % b - c =1+0-3=1-3=-2
1+0 3 1 3 2
e = b = d + c / b – a
Good Programming Practice
• It is best not to take the “big bang” approach to
coding.
coding
• Use an incremental approach by writing your
coded in incomplete,
l yet working,
k pieces.
• Don’t write big expression : break in to smaller
pieces
Good Programming Practice (con’t)
• For example, for your assignments in Lab
– Don’t write the whole program at once.
– Just write enough to display the user prompt on the
screen.
– Get that part working first (compile and run).
– Next,
N write
i the
h part thath gets the
h value
l from
f the
h user, and
d
then just print it out.
– Get that working code(compile and run).
– Next, change the code so that you use the value in a
calculation and print out the answer.
– Get that working (compile and run).
– Continue this process until you have the final version.
– Get the final version working.
• Bottom line: Always have a working version of your
program!