CP Unit -03 Study Material engineering

Download as pdf or txt
Download as pdf or txt
You are on page 1of 29

Unit III – Operators, Expression and Input-Output Operation

Syllabus:

Operators, Types of Operators: Arithmetic, Relational, Logical, Assignment, Increment-


decrement, Conditional, Bitwise, Special. Arithmetic expression, Evaluation of Expression,
Precedence of Arithmetic Operators, Input-Output Operation: Reading and Writing Character,
Formatted Input, Formatted Output.

Contents

1. Operators

2. Types of Operators:

1. Arithmetic

2. Relational

3. Logical

4. Assignment

5. Increment-decrement

6. Conditional

7. Bitwise

8. Special

3. Arithmetic expression

4. Evaluation of Expression

5. Precedence of Arithmetic Operators

6. Input-Output Operation: Reading and Writing Character,

7. Formatted Input

8. Formatted Output
1. OPERATORS:
➢ An operator is a symbol that tells the computer to perform certain mathematical or
logical manipulations.
➢ The operators are used in mathematical or logical expressions.
➢ The C Language supports various operators such as:
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Conditional Operators or ternary operator
5. Bitwise Operators
6. Assignment Operators
7. Increment and Decrement Operators
8. Special Operators

Let us discuss these operators one by one.

2. TYPES OF OPERATOR:

2.1 Arithmetic Operators:

➢ The arithmetic operators are used to perform various arithmetic operations like
addition, subtraction, multiplication and division, etc.

➢ These are binary operators as they take two operands and operand must be numeric
values.

➢ The result of operation will depend upon the type of operands used in instruction.

➢ E.g.

1. c = a + b;

2. z = x * y;

Operator Meaning Example Description

+ Addition a+b Addition of a and b

- Subtraction a–b Subtraction of b from a


* Multiplication a*b Multiplication of a and b

/ Division a/b Division of a by b

% Modulo division- remainder a%b Modulo of a by b

➢ The arithmetic operators are used to perform various arithmetic operations like
addition, subtraction, multiplication and division, etc.

➢ These are binary operators as they take two operands and operand must be numeric
values.

➢ The result of operation will depend upon the type of operands used in instruction.

➢ E.g.

1. c = a + b;

2. z = x * y;

Example:/*Program to convert given number of days to months and days*/

#include<stdio.h>

void main()

int months, days;

printf(“\n Enter days = ”);

scanf(“%d”, &days);

months = days/30;

days = days % 30;

printf(“\n Months =%d and Days = %d ”, months, days);

}
2.2 Relational Operators:

➢ Relational operators are used to compare two numbers and taking decisions
based on their relation.

➢ Relational expressions are used in decision statements such as if, for, while, etc…

➢ Each of these operators compare their Left Side with Right Side.

➢ The complete expression will evaluate to an integer.

➢ If the condition is false, it will evaluate to zero (0).

➢ If the condition is true then it evaluates to 1.

1. We can use the relational operator with if statement to control the flow of execution.

Operator Meaning Example Description

< Is less than a<b a is less than b

<= Is less than or equal to a <= b a is less than or equal to b

> Is greater than a>b a is greater than b

>= Is greater than or equal to a >= b a is greater than or equal to b

== Is equal to a=b a is equal to b

!= Is not equal to a != b a is not equal to b

2.3 Logical Operators:

➢ A logical operator is used to compare or evaluate logical and relational


expression.

➢ Logical operators are used to test more than one condition and make decisions.

➢ Logical AND ( && ):

➢ e.g. A > B && X == 10


➢ Here, both A > B and X == 10 must be true.

➢ Logical OR ( || ):

➢ e.g. A < M || A < N

➢ Here, any one of the conditions A < M or A < N must be true.

➢ Logical NOT ( ! ):

➢ It is an unary operator which takes single operand.

➢ E.g. ! (x>=y).

The expression or operand following ! Must be false.

E.g. To understand the NOT operator.

if( ! (x>y) )

printf(“x is not greater than y”);

2.4 Conditional Operator ( ? : ):

➢ This operator is used to check the condition and has two parts to be executed based
in evaluation of condition. Conditional operator is also known as ternary operator.

➢ Syntax:

➢ exp1 ? exp2 : exp3

exp1 is evaluated first

if exp1 is true(nonzero) then

- exp2 is evaluated and its value becomes the value of the expression

If exp1 is false(zero) then

- exp3 is evaluated and its value becomes the value of the expression

Example: //Program to find largest of two numbers

#include<stdio.h>
void main()

int a, b, large;

a=10; b=20;

large = (a > b) ? a : b ;

printf(“Largest no =%d”, large);

2.5. Assignment Operators:

➢ Assignment operators (=) is used to assign the result of an expression to a variable.

➢ C has two types of assignment operators as simple and ‘shorthand’ assignment


operators(compound assignment operators).

Operator Meaning

= Assigns value of right side to left side

+= a += 1 is same as a = a + 1

-= a -= 1 is same as a = a - 1

*= a *= 1 is same as a = a * 1

/= a /= 1 is same as a = a / 1

%= a %= 1 is same as a = a % 1
Simple Assignment Shorthand Assignment

a=a+1 a += 1

a=a–1 a -= 1

a = a * (n+1) a *= (n+1)

a = a / (n+1) a /= (n+1)

a = a % (n+1) a %= (n+1)

2.6 Increment & Decrement Operators:


➢ Increment (++) operator used to increase the value of the variable by one.
➢ Decrement (--) operator used to decrease the value of the variable by one.
➢ Both increment and decrement operators are unary operators.
➢ They require variables as their operands.
➢ There are two ways how increment and decrement operators are used as prefix and
postfix.
1. Prefix Notation: ++m, --n
2. Postfix Notation: m++, n--

Example Explanation
x=100; After the execution the value of x will be 101.
x++;

Example Explanation
x=100; After the execution the value of x will be 99.
x--;
Operator Description

Pre increment operator value of x is incremented before assigning it to


(++x) the variable on the left

Operator Description

Post increment operator value of x is incremented after assigning it to


(x++) the variable on the left

Rules for ++ and -- Operators

1. When postfix notation is used with a variable in an expression, the expression is


evaluated first using original value of variable and then variable is either incremented
or decremented.

2. When prefix notation is used with variable in an expression, the variable is


incremented or decremented first and then the expression is evaluated.

Example: //Program for increment and decrement

#include<stdio.h>

void main()

int a, b, c, d;

a=10; b=20; c=30; d=40;


printf(“\n a = %d, b = %d, c = %d”, a, b, c );

printf(“\n Prefix increment of a= %d”, ++a);

printf(“\n Postfix increment of b= %d”, b++);

printf(“\n Prefix decrement of c= %d”, --c);

printf(“\n Postfix decrement of d= %d”, d--);

printf(“\n a = %d, b = %d, c = %d”, a, b, c );

Modify Operators :-

Its is also known as Unary Operator.


When Pre Increment , Post Increment and

Pre Decrement and Post Decrement increases the values :-

Example 1:

int main( )

int x = 10 ,y;

y = ++ x;

printf(“%d %d”, x, y);

Output: 11 11
Example 2:

int main( )

int x= 10 ,y;

y = x ++;

printf(“%d %d”, x, y);

Output: 11 10

2.7 Bitwise Operators:

➢ Bitwise operators are used to perform operation bit by bit.

➢ Bitwise operators may not be applied to float or double.

➢ These operators are used for testing , complementing or shifting the bits of binary
data.
Operator Meaning

& bitwise AND

| bitwise OR

^ bitwise exclusive OR

<< shift left (shift left means multiply by 2)

>> shift right (shift right means divide by 2)

~ Bitwise complement

sizeof() operator in C

1. The sizeof() operator is a special operator used to return the size of its operand in
bytes.

2. Example:

1. int a, b;

2. b = sizeof(a);

3. The integer needs 2 bytes to be stored on memory of computer.

4. Hence the value of b will be 2.

5. The sizeof() operator is normally used to identify the length of array.

6. It is used to allocate the memory space dynamically to variables during the execution.

Example: //Program to find sizeof() different data types

#include<stdio.h>

void main()
{

int a, b;

float x = 4.5;

char m = ’A’;

double z = 6.0234;

a = 10;

b = sizeof(a);

printf(“\n Size of integer = %d”, b);

b = sizeof(x);

printf(“\n Size of float = %d”, b);

b = sizeof(m);

printf(“\n Size of character = %d”, b);

b = sizeof(z);

printf(“\n Size of double = %d”, b);

}
Right Shift Operators

1. Representation >>

2. It needs two operands.

3. It Shift each bit from left to right.

4. Examples :- ch>>2 : It will shift all bits of ch by 2 bits towards right,

int a = 10 >>2;

1010 0010 2

#include<stdio.h>

int main( )

int a = 10>>2;

printf(“%d”, a);

getch( );

return 0;

Output : 2

Left Shift Operators

1. Representation <<

2. It needs two operands.

3. It Shift each bit from right to left.

4. Examples :- ch<<2 : It will shift all bits of ch by 2 bits towards left,


int a = 10 << 2;

00001010 00101000 40

#include<stdio.h>

int main( )

int a = 10<<2;

printf(“%d”, a);

getch( );

return 0;

Output : 40

2.8 Special Operators:

Operator Meaning

& Address operator, it is used to determine address of the variable.

* Pointer operator, it is used to declare pointer variable and to get value from it.

, Comma operator. It is used to link the related expressions together.

Sizeof It returns the number of bytes the operand occupies.

. member selection operator, used in structure.

-> member selection operator, used in pointer to structure.


3. ARITHMETIC EXPRESSIONS:

1. An arithmetic Expression is a combination of variables, constants and operators


arranged as per syntax of language.

2. An expression may consist of one or more operands, and zero or more operators to
produce a value.

4. EVALUATION OF EXPRESSIONS:

➢ An expression is evaluated based on the operator precedence and associativity.

➢ When there are multiple operators in an expression, they are evaluated according to
their precedence and associativity.

1. Example:

1. Area-of-C = 3.14 * r * r;

2. Area-of-T = (½) * base * height;

3. Find the output of given program.

//Program to analyze arithmetic expressions

#include<stdio.h>

void main()

{
float a, b, c, x, y, z;

a = 9; b = 12; c = 3;

x = a – b / 3 + c * 2 – 1;

y = a – b / (3 + c) * 2 – 1;

z = a – ( b / (3 + c) * 2) – 1;

printf(“\n x = %f”, x);

printf(“\n y = %f”, y);

printf(“\n z = %f”, z);

Output:-

x = 10.000000

y = 4.000000

z = 4.000000

5. OPERATOR PRECEDENCE:

➢ Operator precedence determines which operator is performed first in an expression


with more than one operators with different precedence.

➢ Precedence of an operator is its priority in an expression for evaluation.

➢ The operator with higher precedence is evaluated first and the operator with the least
precedence is evaluated last.

➢ Operator precedence is why the expression 5 + 3 * 2 is calculated as 5 + (3 * 2),


giving 11, and not as (5 + 3) * 2, giving 16.

➢ We say that the multiplication operator (*) has higher "precedence" or "priority" than
the addition operator (+), so the multiplication must be performed first.
Operator Associativity

➢ Associativity is only used when there are two or more operators of same precedence.

➢ Associativity is the left-to-right or right-to-left order for grouping operands to


operators that have the same precedence.

➢ Operator associativity is why the expression 8 - 3 - 2 is calculated as (8 - 3) - 2, giving


3, and not as 8 - (3 - 2), giving 7.

➢ We say that the subtraction operator (-) is "left associative", so the left subtraction
must be performed first.

➢ When we can't decide by operator precedence alone in which order to calculate an


expression, we must use associativity.

Operator Precedence and Associativity

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & Right to left


sizeof

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right


Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= Right to left


<<= &= ^= |=

Comma , Left to right

Precedence of Arithmetic Operators

1. An arithmetic Expression without parentheses will be evaluated from left to right


using rules of precedence of operators.

2. There are two priority levels:

1. High Priority: *, /, %

2. Low Priority: +, -

3. The expression is evaluated in two left-to-right passes.

4. First pass for the high priority operators

5. Second pass for the low priority operators.

6. Parenthesized sub expressions are evaluated from left-to-right.

7. In case of nesting of parentheses, innermost sub-expression will be evaluated first.

//Program to analyze arithmetic expressions

#include<stdio.h>

void main()

float a, b, c, x, y, z;

a = 9; b = 12; c = 3;
x = a – b / 3 + c * 2 – 1;

y = a – b / (3 + c) * 2 – 1;

z = a – ( b / (3 + c) * 2) – 1;

printf(“\n x = %f”, x);

printf(“\n y = %f”, y);

printf(“\n z = %f”, z);

Output

x = 10.000000

y = 4.000000

z = 4.000000

1. INPUT OUTPUT OPERATIONS:

1. The input and output are two important operations that a C program is expected to do.

2. The input refers to read data from the console for the C program.

3. The output refers to display the data and results generated as a result of execution of a
C program.

4. The C language provides various Input and Output related functions and are classified
as Formatted and Non-formatted Input Output Functions(already covered).

5. We can use scanf() and printf() functions for input and output respectively.

6. Consider an example program which takes input from user and display output.

Input Output Operations – Reading Characters

1. To read the character inputs and display it on the screen as output, we can use %c as a
format specifier.

2. The program is example for reading characters and display it as output can be given
as:
//Program to use character input and output

#include<stdio.h>

void main()

char t;

printf(“\n Enter some Character:”);

scanf(“%c”, &t);

printf(“\n The Character Input = %c”, t);

Output

Enter some Character:M

The Character Input = M

➢ Formatted & Non-formatted I/O Functions

Formatted I/O Functions

1. The formatted Input and Output(I/O) Functions can read and write values of all data
types.

2. We use scanf() as formatted input function and printf() as formatted output


function.

3. We need to use a proper format specifier in both scanf() and printf() functions.

4. Examples of format specifiers are:

1. %d – for integers

2. %c – for characters

3. %f – for float

4. %e – for double
//Program to find largest of two numbers

#include<stdio.h>

void main()

int a, b, big;

a=0; b=0; big=0;

printf(“\n Enter two integers: ”);

scanf(“%d%d”, &a, &b);

big = (a > b) ? a : b ;

printf(“ Largest no =%d”, big);

1. sprintf( ) :

sprintf stands for “string print”. This function is similar to printf( ) function but this function
prints the string into a character array instead of printing it on the console screen.

Syntax:

sprintf(array_name, “format specifier”, variable_name);

2. sscanf( ):

sscanf stands for “string scanf”. This function is similar to scanf() function but this function
reads data from the string or character array instead of the console screen.

Syntax:

sscanf(array_name, “format specifier”, &variable_name);

// C program to implement the sprintf() function

#include <stdio.h>

int main()
{

char str[50];

int a = 2, b = 8;

// The string "2 and 8 are even number"

// is now stored into str

sprintf(str, "%d and %d are even number",a, b);

// Displays the string

printf("%s", str);

return 0;

Out put:

2 and 8 are even number

1. The non-formatted or unformatted Input and Output(I/O) Functions work only with
character data type.

2. We use getch(), getchar(), gets(), getche() as unformatted input functions.

3. We use putch(), putchar(), puts() as unformatted output function.

4. Explanations for unformatted input functions:

1. getch() – It accepts single character from keyboard

2. getche() – It accepts a single character from keyboard and display it on screen.

3. gets() – is used to accept string including spaces from screen.

// C program to implement getch() function

#include <conio.h>

#include <stdio.h>

int main()
{

printf("Enter any character: ");

// Reads a character but not displays

getch();

return 0;

Output:

Enter any character:

6. Explanations for unformatted output functions:

1. putch() – displays any alphanumeric character to standard output screen one


at a time.

2. puts() – It displays a single character or a paragraph text to standard output


screen.

1. Eg: puts(“Your bike is Honda”);

3. putchar() - It displays only one character at a time to the output screen.

1. E.g. putchar(variable_name);

2. putchar(x).

// C program to implement the getche() function

#include <conio.h>

#include <stdio.h>

int main()

printf("Enter any character: ");

// Reads a character and displays immediately


getche();

return 0;

Enter any character: t

getchar( ) :

The getchar( ) function is used to read only a first single character from the keyboard
whether multiple characters is typed by the user and this function reads one character at
one time until and unless the enter key is pressed. This function is declared in
stdio.h(header file)

Syntax:

Variable-name = getchar();

// C program to implement the getchar() function

#include <conio.h>

#include <stdio.h>

int main()

// Declaring a char type variable

char ch;

printf("Enter the character: ");

// Taking a character from keyboard

ch = getchar();

// Displays the value of ch

printf("%c", ch);

return 0;
}

Enter the character: J

putchar( ):

The putchar() function is used to display a single character at a time by passing that
character directly to it or by passing a variable that has already stored a character. This
function is declared in stdio.h(header file)

Syntax:

putchar(variable_name);

// C program to implement the putchar() function

#include <conio.h>

#include <stdio.h>

int main()

char ch;

printf("Enter any character: ");

// Reads a character

ch = getchar();

// Displays that character

putchar(ch);

return 0;

}
Output:

Enter any character: Q

gets():

gets() function reads a group of characters or strings from the keyboard by the user and
these characters get stored in a character array. This function allows us to write space-
separated texts or strings. This function is declared in stdio.h(header file).

Syntax:

char str[length of string in number]; //Declare a char type variable of any length

gets(str);

// C program to implement the gets() function

#include <conio.h>

#include <stdio.h>

int main()

// Declaring a char type array

// of length 50 characters

char name[50];

printf("Please enter some texts: ");

// Reading a line of character or a string

gets(name);

// Displaying this line of character or a string


printf("You have entered: %s", name);

return 0;

Output:

Please enter some texts: SSGMCE Shegaon

You have entered: SSGMCE Shegaon

puts():

In C programming puts() function is used to display a group of characters or strings


which is already stored in a character array. This function is declared in stdio.h(header
file).

Syntax:

puts(identifier_name );

// C program to implement the puts() function

#include <stdio.h>

int main()

char name[50];

printf("Enter your text: ");

// Reads string from user

gets(name);

printf("Your text is: ");

// Displays string

puts(name);
return 0;

Output:

Enter your text: SSGMCE Shegaon

Your text is: SSGMCE Shegaon

Assignment Questions:

1. Explain different types of operators in c.


2. Explain in details various functions for reading and writing character.
3. Explain relational operator in details.
4. Explain any three function of reading and writing characters.
5. Explain following terms.
1. Increment operator
2. Conditional operator
3. Bitwise operator
6. All Problem that ask previous year question paper.

You might also like