0% found this document useful (0 votes)
4 views55 pages

lecture 2

The document provides an overview of fundamental concepts in computer programming, specifically focusing on symbolic constants, variable declarations, assignment statements, and various types of operators in C language. It covers the syntax and rules for defining constants, the purpose of variable declarations, and the use of different operators including arithmetic, relational, logical, and bitwise operators. Additionally, it discusses input/output operations, type conversion, and formatting control strings for output in C.

Uploaded by

21je0842
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)
4 views55 pages

lecture 2

The document provides an overview of fundamental concepts in computer programming, specifically focusing on symbolic constants, variable declarations, assignment statements, and various types of operators in C language. It covers the syntax and rules for defining constants, the purpose of variable declarations, and the use of different operators including arithmetic, relational, logical, and bitwise operators. Additionally, it discusses input/output operations, type conversion, and formatting control strings for output in C.

Uploaded by

21je0842
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/ 55

Computer Programming[CSI101]

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

• Usually defined at the beginning of the program


• Preprocessor replaces each defined name with its corresponding value wherever it is found in the
source program

• 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

• C supports two types of commenting


• // is used to comment a single statement
• This is known as a line comment
• A line comment can be placed anywhere on the line and it does not require to be
specifically ended as the end of the line automatically ends the line.
• /* is used to comment multiple statements
• A /* is ended with */
• All statements that lie within these characters are commented
OPERATORS
Operators in C
• C language supports a lot of operators to be used in expressions. These operators can be
categorized into the following major groups:
1. Arithmetic operators
2. Relational Operators
3. Equality Operators
4. Logical Operators
5. Unary Operators
6. Conditional Operators
7. Bitwise Operators
8. Assignment operators
9. Comma Operator
10. Sizeof Operator
Arithmetic Operator

Operation Operator Syntax Comment Result

Multiply * x*y result = x * y x = 9, y =3,


result = 27

Divide / x/y result = x / y 3

Addition + x+y result = x + y 12

Subtraction - x-y result = x - y 6

Modulus % x%y result = x % y 0


Relational Operator
• Compares two values
• Expressions that contain relational operators are called relational expressions
• Relational operators return true or false value, depending on whether the conditional relationship
between the two operands holds or not

OPERATOR MEANING EXAMPLE

< LESS THAN 3 < 9 GIVES 1

> GREATER THAN 4 > 9 GIVES 0

LESS THAN OR EQUAL


>= 150 >= 150 GIVES 1
TO
GREATER THAN
<= 90 >=100 GIVES 0
EQUAL TO
Equality Operator
• C language supports two kinds of equality operators to compare their operands for strict equality or
inequality
• They are equal to (==) and not equal to (!=) operator

OPERATOR MEANING

== RETURNS 1 IF BOTH OPERANDS ARE EQUAL, 0 OTHERWISE

!= RETURNS 1 IF OPERANDS DO NOT HAVE THE SAME VALUE, 0


OTHERWISE
Logical Operator
• C language supports three logical operators
• Logical AND (&&), Logical OR (||) and Logical NOT (!)

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

• exp1 is evaluated first


• If it is true
• exp2 is evaluated and becomes the result of the expression

• otherwise exp3 is evaluated and becomes the result of the expression


• Example
• large = ( a > b) ? a : b
• a = 5, b =2 è large = 5
Bitwise Operator
• Bitwise operators perform operations at bit level
• Bitwise AND (&)
• Small version of boolean AND (&&)
• Performs operation on bits instead of bytes, chars, integers, etc.
• Bitwise OR (|)
• small version of the boolean OR (||)
• Performs operation on bits instead of bytes, chars, integers, etc.
• Bitwise NOT (~)
• Unary operation that performs logical negation on each bit of the operand
• Bitwise XOR (^) A B A^B

• Performs operation on individual bits of the operands 0 0 0


0 1 1
1 0 1
1 1 0
Bitwise Shift Operator
• The digits are moved, or shifted, to the left or right
• The CPU registers have a fixed number of available bits for storing numerals
• When we perform shift operations; some bits will be "shifted out" of the register at one end,
while the same number of bits are "shifted in" from the other end.

• In a left shift (<<), zeros are shifted in on the right 1 1 0 0 0 1 0 1

• unsigned int x = 11000101;


<<1 1 0 0 0 1 0 1 0 Empty box is 0
• x << 2 = 00010100

<<1 0 0 0 1 0 1 0 0 Empty box is 0

• 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 = expression variable = expression Fundamental assignment operator

*= variable *= expression variable = variable * expression Multiply and assignment operator

Divide and assignment operator


/= variable /= expression variable = variable / expression

%= variable %= expression variable = variable % expression Modulus and assignment operator

+= variable += expression variable = variable + expression Add and assignment operator

-= variable -= expression variable = variable - expression Subtract and assignment operator

<<= 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

|= variable |= expression variable = variable | expression Bitwise OR and assignment operator


Comma Operator
• The comma operator in C takes two operands
• It works by evaluating the first and discarding its value, and then evaluates the second and
returns the value as the result of the expression

• 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

Equality Operators == != LèR


Bitwise AND Operator & LèR
Bitwise XOR Operator ^ LèR
Bitwise OR Operator | LèR

Logical AND Operator && LèR


Logical OR Operator || LèR

Conditional Operator ?: RèL

Assignment Operator = += -= *= /= %=>>= <<= &= ^= |= RèL


Comma Operator , 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+d%e–f è a * (-b) + (d%e) - f

• 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

• Integer arithmetic always yields integer values


Real Arithmetic
• Arithmetic operations involving only real or floating-point operands

• Since floating-point values are rounded to the number of significant digits


permissible, the final value is an approximation of the final result
• 1.0 / 3.0 * 3.0 will have the value 0.99999 and not 1.0

• The modulus operator cannot be used with real operands


Mixed-mode 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

• Control string format:


• %[flags][width][.precision][length]specifier
I/O - Control String
%[flags][width][.precision][length]specifier

• 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

0 Causes leading zeros to appear instead of leading blanks e.g., [0007]

Causes octal and hexadecimal data items to be preceded by 0 and 0X


#
[Without this 0xa08c is printed as a08c]

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

h When the argument is a short int or unsigned short int

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

f Data item is displayed as a floating point value without exponent

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]

s Data item is displayed as a string


u Data item is displayed as an unsigned decimal integer

x, X Data item is displayed as a hexadecimal integer without leading 0x [0x08ac è 08ac]


Input/ Output
• scanf

• 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

• It is required to put an ampersand (&) before the names of the variables

• General syntax:
• scanf(“control string”, arg1, arg2, …, argn);

• Control string format:


• %[*][width][modifiers][type]
I/O - Control String
%[*][width][modifiers][type]

• Width
• Can be specified by an unsigned integer

• Number of characters in data item < specified width field


• Accepted

• Number of characters in data item > specified width field


• Extra characters will not be read
• May be incorrectly interpreted as the components of next item
I/O - Control String - Modifiers
%[*][width][modifiers][type]

Modifiers indicate the length of the corresponding argument

Length Description

h When the argument is a short int or unsigned short int

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

f Data item is displayed as a floating point value without exponent

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]

s Data item is displayed as a string


u Data item is displayed as an unsigned decimal integer

x, X Data item is displayed as a hexadecimal integer without leading 0x [0x08ac è 08ac]


Example - scanf/printf
• int num;
• float fnum;
• char ch, str[10];
• short snum;
• long int lnum;

• printf(“\n Enter the values : ”);


• scanf("%d %f %hd %ld", &num, &fnum, &snum, &lnum);
• scanf("%c %s", &ch, str);

• 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?

• Using relational operators


• Four relation operators
• < <= > >=
• Two equality operators
• == !=

• Using logical operators / connectives


• Two logical connectives
• && ||
• Unary negation operator
• !
Expressions
• (count<=100)

• ((math + phys + chem + bio)/4 >= 80)

• ((marks>=80) && (marks<90))

• (marks>=80 && marks<90)

• (balance>10000 || no_of_trans < 25)

• (!(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 condition to be tested is any expression enclosed in parentheses

• 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

OUTPUT A OUTPUT FAIL


OUTPUT EX

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

• All if statements may not having the else part

• Rule:
• An “else” clause is associated with the closest preceding unmatched “if”
Example 2: Grade Computation
int main() int main()

{ {

int marks; int marks;


print(“Enter marks\n”);
print(“Enter marks\n”);
scanf(“%d”, &marks);
scanf(“%d”, &marks);
if (marks>90){
if (marks>90){
printf(“EXCELLENT (EX)\n”);
printf(“EXCELLENT (EX)\n”);
}
}
else{
else if (marks>80){ if (marks>80){
printf(“GOOD (A)\n”); printf(“GOOD (A)\n”);
} }
else{ else{

printf(“FAIL\n”); printf(“FAIL\n”);

printf(“Give Effort for Supplementary\n”); printf(“Give Effort for


Supplementary\n”);
}
}
} }
}

You might also like