col100 - indian institute of technology delhirahulgarg/teaching/2017/col100-class-7.pdf · two...
TRANSCRIPT
COL100
2
First C program – print on screen
#include <stdio.h> void main() {
printf (“Who am I?\n") ; }
3
More printing …
#include <stdio.h> void main() {
printf (“Who am I?") ; printf (“Who \n am\n I?\n") ;
}
4
Some more printing #include <stdio.h> void main() {
printf (“Who am I?\n") ; printf (“Who") ; printf (“am") ; printf (“I?\n") ;
}
5
Some more printing #include <stdio.h> void main() {
printf (“Who am I?\n") ; printf (“Who ") ; printf (“am ") ; printf (“I?") ; printf(“\n”);
}
6
#include <stdio.h>void main(){ int num ;
printf(“Please type a number:”); scanf ("%d", &num) ; printf (“You typed %d\n”, num) ;}
Reading values from keyboard
7
Centigrade to Fahrenheit
#include <stdio.h>void main(){ float cent, fahr;
scanf(“%f”,¢); fahr = cent*(9.0/5.0) + 32; printf( “%f C equals %f F\n”, cent, fahr);}
8
Variables
Very important concept for programming An entity that has a value and is known to the program by a name Can store any temporary result while executing a program Can have only one value assigned to it at any given time during the execution of the program The value of a variable can be changed during the execution of the program
9
Contd.Variables stored in memory Remember that memory is a list of storage locations, each having a unique address A variable is like a bin ◻The contents of the bin is the value of the variable ◻The variable name is used to refer to the value of
the variable ◻A variable is mapped to a location of the memory,
called its address
10
Example
#include <stdio.h> void main( ) { int x; int y; x=1; y=3; printf("x = %d, y= %d\n", x, y); }
11
Variables in MemoryInstruction executed Memory location allocated
to a variable X
T i
m e
X = 10
10X = 20
X = X +1
X = X*5
12
Variables in MemoryInstruction executed Memory location allocated
to a variable X
T i
m e
X = 10
20X = 20
X = X +1
X = X*5
13
Variables in MemoryInstruction executed Memory location allocated
to a variable X
T i
m e
X = 10
21X = 20
X = X +1
X = X*5
14
Variables in MemoryInstruction executed
Memory location allocated to a variable X
T i
m e
X = 10
105X = 20
X = X +1
X = X*5
15
Variables (contd.)
20
?
X
Y
X = 20
Y=15
X = Y+3
Y=X/6
16
Variables (contd.)
20
15
X
Y
X = 20
Y=15
X = Y+3
Y=X/6
17
Variables (contd.)
18
15
X
Y
X = 20
Y=15
X = Y+3
Y=X/6
18
Variables (contd.)
18
3
X
Y
X = 20
Y=15
X = Y+3
Y=X/6
Variables
Must be declared before use
Declaration must have ◻Variable type ◻Variable name ◻Optionally – variable’s initial value
19
Variable TypesBasic variable types ◻char - can store a character (1 byte) ◻int - can store integers (usually 4 bytes) ◻float - can store single-precision floating point numbers (usually 4
bytes) ◻double - can store double-precision floating point numbers (usually
8 bytes) Qualifiers ◻short, long (for int) ◻unsigned (for char, int)
20
Variable type examples
21
Variable type examples
22
Other Variable Types
Structures – struct Unions – union Enumerated – enum Arrays – [] Pointers – *, -> User defined variable types -- typedef
23
24
Variable NamesSequence of letters and digits First character must be a letter or ‘_’ No special characters other than ‘_’ No blank in between Names are case-sensitive ◻max and Max are two different names
Examples of valid names: ◻ i rank1 MAX max Min class_rank
Examples of invalid names: ◻a’s, fact rec, 2sqroot, class,rank
More Valid and Invalid Identifiers
X abc 10abc simple_interest my-name my_name a123 “hello” stud_name simple interest
(area) Empl_1 Empl_2 avg_empl_salary % LIST rate char __UGLY_VARIABLE
More Valid and Invalid Identifiers
Valid identifiers X abc simple_interest a123 LIST stud_name Empl_1 Empl_2 avg_empl_salary
Invalid identifiers 10abc my-name “hello” simple interest (area) %rate char
C Keywords
Used by the C language, cannot be used as variable names Examples: ◻int, float, char, double, main, if else, for, while. do, struct, union,
typedef, enum, void, return, signed, unsigned, case, break, sizeof,….
Variable names cannot be a C keyword But can contain keywords
Complete List of 32 C Keywords
28
29
The C Character SetThe C language alphabet ◻Uppercase letters ‘A’ to ‘Z’ ◻Lowercase letters ‘a’ to ‘z’ ◻Digits ‘0’ to ‘9’ ◻Certain special characters:
A C program should not contain anything else
! # % ^ & * ( )
- _ + = ~ [ ] \
| ; : ‘ “ { } ,
. < > / ? blank
More Valid and Invalid Identifiers
int_32 Float double if my_double _double C_is_great character Char char
long_char cHar inT long_int Then Long long unsigned unSigned else
31
Example 1
#include <stdio.h>void main(){ int x, y, sum;
scanf(“%d%d”,&x,&y); sum = x + y; printf( “%d plus %d is %d\n”, x, y, sum );}
Three int type variables declared
Values assigned
32
Example – 2 (variable initialization)
#include <stdio.h>void main(){ float x = 3.1415, y; int d1, d2 = 10;
printf( “x = %f\ny = %f\n”, x, y); printf( “d1 = %d\nd2 = %d\n”, d1, d2); }
Assigns an initial value to d2, can be changed later
33
Example - 3
#include <stdio.h>void main(){ float x, y; int d1, d2 = 10;
scanf(“%f%f%d”,&x, &y, &d1); printf( “%f plus %f is %f\n”, x, y, x+y); printf( “%d minus %d is %d\n”, d1, d2, d1-d2); }
Assigns an initial value to d2, can be changed later
34
ConstantsInteger constants FP constants Character constants
35
Integer constantsConsists of a sequence of digits, with possibly a plus or a minus sign before it Embedded spaces, commas and non-digit characters are not permitted between digits Example of valid and invalid integer constants
36
Floating point constantsTwo different notations: ◻Decimal notation: 25.0, 0.0034, .84, -2.234 ◻Exponential (scientific) notation
3.45e23, 0.123e-12, 123e2 Embedded spaces, commas and non-digit characters are not permitted between digits Example of valid and invalid floating point constants
e means “10 to the power of”
37
Character constants◻Contains a single character enclosed within a pair of
single quote marks. ◻Examples :: ‘2’, ‘+’, ‘Z’
Some special backslash characters ‘\n’ new line ‘\t’ horizontal tab ‘\’’ single quote ‘\”’ double quote ‘\\’ backslash ‘\0’ null
String – A sequence of characters enclosed in double quotes. e.g. –
38
39
Expressions
40
ExpressionsVariables and constants linked with operators ◻Arithmetic expressions
Uses arithmetic operators Can evaluate to any value
◻Logical expressions Uses relational and logical operators Evaluates to 1 or 0 (true or false) only
◻Bit-wise expressions Uses bitwise operators Works on char, short, int and long
What is an expression?
expression := constant OR variable OR function call OR expression operator expression OR (expression)
41
42
Arithmetic Operators and ExpressionsBinary operators ◻Addition: + ◻Subtraction: – ◻Division: / ◻Multiplication: * ◻Modulus: %
Unary operators ◻Plus: + ◻Minus: –
2*3 + 5 – 10/3 –1 + 3*25/5 – 7 distance / time 3.14* radius * radius a * x * x + b*x + c dividend / divisor 37 % 10
Examples
43
Contd.Suppose x and y are two integer variables, whose values are 13 and 5 respectively
x + y 18x – y 8x * y 65x / y 2
x % y 3
44
All operators except % can be used with operands of all of the data types int, float, double, char (yes! char also! We will see what it means later) % can be used only with integer operands
45
Operator PrecedenceIn decreasing order of priority
1. Parentheses :: ( ) 2. Unary minus :: –5 3. Multiplication, Division, and Modulus 4. Addition and Subtraction
For operators of the same priority, evaluation is from left to right as they appear Parenthesis may be used to change the precedence of operator evaluation
46
Examples: Arithmetic expressions
a + b * c – d / e a + (b * c) – (d / e)
a * – b + d % e – f a * (– b) + (d % e) – f
a – b + c + d (((a – b) + c) + d)
x * y * z ((x * y) * z)
a + b + c * d * e (a + b) + ((c * d) * e)
47
Type of Value of an Arithmetic Expression
If all operands of an operator are integer (int variables or integer constants), the value is always integer ◻Example: 9/5 will be 1, not 1.8 ◻Example: int a=9, b=5; printf(“%d”, a/b) will print 1 and not 1.8
General rule for determining type of an expression
In case of two operands of different types, the result is upgraded to higher type char < int < float < double eg. int a = 10, b = 4; float c;
c = a / b;
48
49
Type of the expression
The type of the final value of the expression can be found by applying these rules again and again as the expression is evaluated following operator precedence
50
If at least one operand is real, the value is real ◻Caution: Since floating-point values are rounded to the number of
significant digits permissible, the final value is an approximation of the final result
◻ Example: 1/ 3.0 * 3.0 may have the value 0.99999 and not 1.0 ◻So checking if 1/ 3.0 * 3.0 is equal to 1.0 may return false!!
51
We have a problem!!int a=10, b=4, c; float x; c = a / b; x = a / b;
The value of c will be 2 The value of x will be 2.0 But we want 2.5 to be stored in x
We will take care of this a little later
52
Assignment OperatorUses the assignment operator (=) General syntax:
variable_name = expression Left of = is called l-value, must be a modifiable variable Right of = is called r-value, can be any expression Examples:
velocity = 20 b = 15; temp = 12.5 A = A + 10 v = u + f * t s = u * t + 0.5 * f * t * t
53
Contd.An assignment operator evaluates to a value same as any other expression Value of an assignment operator is the value assigned to the l-value Example: value of ◻a = 3 is 3 ◻b = 2*4 – 6 is 2 ◻n = 2*u + 3*v – w is whatever the arithmetic
operator 2*u + 3*v – w evaluates to given the current values stored in variables u, v, w
54
Contd.Several variables can be assigned the same value using multiple assignment operators a = b = c = 5; flag1 = flag2 = ‘y’; speed = flow = 0.0;
Easy to understand if you remember that ◻ the assignment operator has a value ◻Multiple assignment operators are right-to-left
associative
55
ExampleConsider a= b = c = 5 ◻Three assignment operators ◻Rightmost assignment expression is c=5, evaluates to
value 5 ◻Now you have a = b = 5 ◻Rightmost assignment expression is b=5, evaluates to
value 5 ◻Now you have a = 5 ◻Evaluates to value 5 ◻So all three variables store 5, the final value the
assignment expression evaluates to is 5
56
Types of l-value and r-valueUsually should be the same If not, the type of the r-value will be internally converted to the type of the l-value, and then assigned to it Example: double a; a = 2*3; Type of r-value is int and the value is 6 Type of l-value is double, so stores 6.0
57
This can cause strange problems int a; a = 2*3.2;
Type of r-value is float/double and the value is 6.4 Type of l-value is int, so internally converted to 6 So a stores 6, not the correct result But an int cannot store fractional part anyway So just badly written program Be careful about the types on both sides
58
More Assignment Operators+=, -=, *=, /=, %= Operators for special type of assignments a += b is the same as a = a + b Same for -=, *=, /=, and %= Exact same rules apply for multiple assignment operators
59
Contd.Suppose x and y are two integer variables, whose values are 5 and 10 respectively.
x += y Stores 15 in x Evaluates to 15
x –= y Stores -5 in x Evaluates to -5
x *= y Stores 50 in x Evaluates to 50
x /= y Stores 0 in x Evaluates to 0
60