lecture 2
lecture 2
Koustav Rudra
I/O, Operator, Expression
31/05/2022
Symbolic Constants
• A symbolic constant is a name that substitutes for a sequence of characters
• Allows a name to appear in place of a numeric/ character/ string constant
• General Syntax:
• #define name text
• Example:
• #define A 5
• #define XZ ‘C’
Symbolic Constants: Rules
• Constant names are usually written in capital letters [CONVENTION not RULE]
• No blank spaces are permitted in between the # symbol and define keyword
• Blank space must be used between #define and constant name and between constant name and
constant value
• #define is a preprocessor compiler directive and not a statement. Therefore, it does not end with
a semi-colon
Variable Declaration
• There are two purposes:
• It tells the compiler what the variable name is
• It specifies what type of data the variable will hold [int/float/long]
• General syntax:
• data-type variable-list;
• Examples:
• int velocity, distance;
• int a, b, c, d;
• float temp;
• char flag, option;
Assignment Statement
• Used to assign values to variables, using the assignment operator (=)
• General syntax:
• variable_name = expression; ; is must at the end
Common mistake for programmers
• Examples:
• velocity = 20;
• b = 15; temp = 12.5; A = A + 10;
• v = u + f * t;
• s = u * t + 0.5 * f * t * t;
Assignment Statement
• A value can be assigned to a variable at the time the variable is declared
• int velocity = 30;
• char flag = ‘y’;
Data-type Identifier
• Several variables can be assigned the same value using multiple assignment
operators
• x = y = z = 7;
• flag1 = flag2 = ‘y’;
• velocity = flow = 0.3;
• Multiple variables can be initialized in the same line using comma
• int x=5, y=7;
Comments
• Comments are just a way of explaining what a program does
• It is merely an internal program documentation
• The compiler ignores the comments when forming the object file
• This means that the comments are non-executable statements
OPERATOR MEANING
A B A &&B A B A ||B A !A
0 0 0 0 0 0
0 1
0 1 0 0 1 1
1 0
1 0 0 1 0 1
1 1 1 1 1 1
Unary Operator
• Unary operators act on single operands
• C language supports three unary operators ---- unary minus, increment and decrement operators
• Unary minus
• When an operand is preceded by a minus sign, the unary operator negates its value
• Unary increment
• The increment operator is a unary operator that increases the value of its operand by 1
• x++ è x = x + 1
• Unary decrement
• Similarly, the decrement operator decreases the value of its operand by 1
• x-- è x = x - 1
Conditional Operator [Ternary]
• General syntax
• exp1 ? exp2 : exp3
• If a right shift (>>) is performed on an unsigned integer then zeros are shifted on the left
• unsigned int x = 11000101;
• x >> 2 = 00110001
Assignment Operators
OPERATOR SYNTAX EQUIVALENT TO DESCRIPTION
<<= variable <<= amount variable = variable << amount Left shift and assignment operator
>>= variable >>= amount variable = variable >> amount Right shift and assignment operator
&= variable &= expression variable = variable & expression Bitwise AND and assignment operator
^= variable ^= expression variable = variable ^ expression Bitwise XOR and assignment operator
• Comma separated operands when chained together are evaluated in left-to-right sequence with the
right-most value yielding the result of the expression
• For example,
int a=2, b=3, x=0;
x = (++a, b+=a);
Now, the value of x = 6.
Sizeof Operator
• sizeof is a unary operator used to calculate the sizes of data types
• It can be applied to all data types
• The operator returns the size of the variable, data type or expression in bytes
• Example:
• int a = 10;
• unsigned int result;
• result = sizeof(a);
• then result = 4
Precedence and Associativity
• Precedence
• Precedence is the priority for grouping different types of operators with their operands
• Associativity
• Associativity is the left-to-right or right-to-left order for grouping operands to operators that
have the same precedence
Operator Precedence
Operator Category Operators Associativity
Unary operators - ++ -- !~ sizeof (type) RèL
Arithmetic multiply, divide, modulus */ % LèR
Arithmetic add, subtract +- LèR
Shift Operators << >> LèR
Relational Operators < <= > >= LèR
• 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
Examples: Arithmetic Expressions
• a+b*c–d/e è a + (b * c) - (d / e)
• a–b+c+d è (((a-b)+c)+d)
Integer Arithmetic
• When the operands in an arithmetic expression are integers, the expression is
called integer expression, and the operation is called integer arithmetic
• When one of the operands is integer and the other is real, the expression is called a
mixed-mode arithmetic expression.
• If either operand is of the real type, then only real arithmetic is performed, and the
result is a real number.
• 25 / 10 è 2
• 25 / 10.0 è 2.5
Type Conversion
• Changing a variable of one data type into another
• Type conversion is done implicitly
• Type conversion is done when the expression has variables of different data types
• To evaluate the expression, the data type is promoted from lower to higher level
• The hierarchy of data types can be given as: double, float, long, int, short and char
• Example:
• float x;
• int y = 3;
• x = y;
• Now, x = 3.0
Type Casting
• Type casting is also known as forced conversion
• Type casting is done explicitly
• Value of a higher data type has to be converted in to the value of a lower data type
• Typecasting can be done by placing the destination data type in parentheses followed by the
variable name that has to be converted
• Example:
• float salary = 10000.00;
• int sal;
• sal = (int) salary;
Input/ Output
• printf
• Performs output to the standard output device (typically defined to be the screen)
• General syntax:
• printf(“control string”, variable list);
• Control string defines the format in which variables are printed on the screen
• Width
• Can be specified by an unsigned integer
• Number of characters in data item < specified width field
• Data item will be preceded by leading blanks [width 4, print 7 è \b\b\b7]
• Number of characters in data item > specified width field
• Additional space will be allocated to print entire data item
• Precision
• Maximum number of decimal places for a floating point value
• Maximum number of characters for a string
• A floating point number is rounded if it must be shortened to conform to a precision
specification
I/O - Control String - Flag
%[flags][width][.precision][length]specifier
Flag affects the appearance of the output
Flag Description
Data item is left justified within the field. Blank spaces required to fill the width will be
-
added after the data e.g., [7\b\b\b] è width 4
Displays the data with numeric sign (+ or -). Without this, only negative items are
+
preceded by - sign
Causes a decimal point to be present in all floating point numbers, even if the data item
# is a whole number [12.0 è 12.]
Prevent truncation of trailing zeros in g-type conversion [e.g., -3.3 è -3.30]èwidth 4
I/O - Control String - Length
%[flags][width][.precision][length]specifier
Lengths are prefixes within control string to indicate the length of the corresponding argument
Length Description
l When the argument is a long int or unsigned long int for integer specifiers
L When the argument is a long double (used for floating point specifiers)
I/O - Control String - Specifier
%[flags][width][.precision][length]specifier
Specifier Qualifying Input
c Data item is displayed as a single character
d Data item is displayed as a signed decimal integer
e, E Data item is displayed as a floating point value with an exponent [-3.3e +00]
Data item is displayed as a floating point value using either e/f type conversion
g, G
depending on the value. Trailing zeros and decimal point will not be displayed [-3.3]
o Data item is displayed as an octal integer without a leading zero [0177è177]
• Performs input from the standard input device, which is the keyboard by default
• It requires a format string and a list of variables into which the value received from the input device will
be stored
• General syntax:
• scanf(“control string”, arg1, arg2, …, argn);
• Width
• Can be specified by an unsigned integer
Length Description
l When the argument is a long int or unsigned long int for integer specifiers
L When the argument is a long double (used for floating point specifiers)
I/O - Control String - type
%[*][width][modifiers][type]
Specifier Qualifying Input
c Data item is displayed as a single character
d Data item is displayed as a signed decimal integer
e, E Data item is displayed as a floating point value with an exponent [-3.3e +00]
Data item is displayed as a floating point value using either e/f type conversion
g, G
depending on the value. Trailing zeros and decimal point will not be displayed [-3.3]
o Data item is displayed as an octal integer without a leading zero [0177è177]
• printf("num = %d fnum = %.2f snum = %hd lnum = %ld\n", num, fnum, snum, lnum);
• printf("ch = %c str=%s\n", ch, str);
Sample Program
#include<stdio.h>
#include<stdlib.h>
int main()
{
printf(“Welcome to C Programming course\n”);
return 0;
}
Control Flow: Branching
31/05/2022
Statements and Blocks
• An expression followed by a semicolon becomes a statement
• Examples:
• x++;
• i = 7;
• printf(“The sum is = %d\n”, sum);
• Braces { and } are used to group declarations and statements together into a compound statement,
or block
{
sum = sum + count;
count--;
printf(“Sum = %d\n”, sum);
}
Control Statements: Role
• Branching:
• Allow different sets of instructions to be executed depending on the outcome of a logical test
• Whether TRUE (non-zero) or FALSE (zero)
• Looping:
• Some applications may also require that a set of instructions be executed repeatedly, possibly
again based on some condition
How to specify conditions?
• (!(grade==‘A’))
Evaluation of conditions
• Zero
• Indicate FALSE
• Non-zero
• Indicates TRUE
• Typically the condition TRUE is represented by value ‘1’
Branching: if statement
if (expression)
statement;
if (expression) {
Block of statements;
}
• The expression is evaluated, and if its value is non-zero, the statement is executed
A decision can be made on
any expression
Zero – FALSE
Non-zero - TRUE
TRUE printf(“Great Job”);
marks>=90 printf(“Good Luck”);
FALSE
if (marks>=90) {
printf(“Great Job”);
Printf(“Good Luck”);
}
Branching: if-else statement
if (expression) { if (expression) {
Block of statements; Block of statements;
} }
else { else if (expression) {
Block of statements; Block of statements;
} }
else {
Block of statements;
}
Example 1: Grade Computation
START
int main()
READ MARKS {
int marks;
print(“Enter marks\n”);
No scanf(“%d”, &marks);
MARKS >=
40? if (marks>40)
{
Yes printf(“PASS\n”);
}
OUTPUT PASS OUTPUT FAIL else
{
printf(“FAIL\n”);
}
STOP STOP }
Example 2: Grade Computation
START
READ MARKS
No No
MARKS >= MARKS >=
90? 80?
Yes Yes
STOP STOP
STOP
Example 2: Grade Computation
int main()
{
int marks;
print(“Enter marks\n”);
scanf(“%d”, &marks);
if (marks>90){
printf(“EXCELLENT (EX)\n”);
}
else if (marks>80){
printf(“GOOD (A)\n”);
else{
printf(“FAIL\n”);
printf(“Give Effort for Supplementary\n”);
}
}
Confusing Equality(==) and Assignment (=) Operator
• Dangerous Error
• Does not cause syntax errors
• Any expression that produces a value can be used in control structures
• Nonzero values are TRUE, zero values are FALSE
• Example
if(GRADE==‘A’) {
printf(“EX\n”);
}
if(GRADE=‘A’){
printf(“EX\n”); Wrong
}
Nesting if-else structure
• It is possible to nest if-else statements, one within another
• Rule:
• An “else” clause is associated with the closest preceding unmatched “if”
Example 2: Grade Computation
int main() int main()
{ {
printf(“FAIL\n”); printf(“FAIL\n”);