0% found this document useful (0 votes)
19 views17 pages

CPDS_UNIT-1(Part-2)_Notes

C programing
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)
19 views17 pages

CPDS_UNIT-1(Part-2)_Notes

C programing
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/ 17

UNIT-I Prepared by Mr. B. Kesava Rao, Asst.Porf., ECE.

Structure of a C Program – Operators, Bit-wise operators, Expressions, Precedence and


Associatively, Expression Evaluation, Type conversions and casting.

C-Operators
 An operator is a symbol used to perform arithmetic and logical operations in a
program.
 That means an operator is a special symbol that tells the compiler to perform
mathematical or logical operations.
 C programming language supports a rich set of operators that are classified as
follows.

1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Increment & Decrement Operators
5. Assignment Operators
6. Bitwise Operators
7. Conditional Operator
8. Special Operators

1. Arithmetic Operators (+, -, *, /, %):


 The arithmetic operators are the symbols that are used to perform basic
mathematical operations like addition, subtraction, multiplication, division and
percentage modulo.

The following table provides information about arithmetic operators.

Operator Meaning Example


+ Addition 8 + 4 = 12
- Subtraction 8-4=4
* Multiplication 8 * 4 = 32
/ Division 8/4=2
% Remainder of the division 5%2=1

 The addition operator can be used with numerical data types and character data
type. When it is used with numerical values, it performs mathematical addition
and when it is used with character data type values, it performs concatenation
(appending).
 The remainder of the division operator is used with integer data type only.
Example: Write a C program to illustrate arithmetic operators.

/* Arithmetic Operator * / % + - */

#include<stdio.h>
int main()
{
int a,b,c;
float x;
printf("\nEnter 2 Nos : ");
scanf("%d%d",&a,&b);
c=a+b;
printf("\nTotal : %d",c);
c=a-b;
printf("\nDifference : %d",c);
c=a*b;
printf("\nMul : %d",c);
x=(float)a/(float)b;
printf("\nDiv : %0.2f",x);
c=a%b;
printf("\nMod : %d",c);
return 0;
}

2. Relational Operators (<, >, <=, >=, ==, !=):


 The relational operators are the symbols that are used to compare two values.
That means the relational operators are used to check the relationship between
two values.

 Every relational operator has two results TRUE or FALSE. In simple words, the
relational operators are used to define conditions in a program.

 The following table provides information about relational operators.


Example: C Program for illustration of relational operators

//Relational Operators
#include<stdio.h>
int main()
{
int a=10,b=5;
printf("Greater Than : %d",a>b);
printf("\nLess Than : %d",a<b);
printf("\nGreater Than or Equal : %d",a>=b);
printf("\nLesser Than or Equal : %d",a<=b);
printf("\nEqual : %d",a==b);
return 0;
}
OutPut:
Greater Than : 1
Less Than : 0
Greater Than or Equal : 1
Lesser Than or Equal : 0
Equal : 0

3. Logical Operators (&&, ||, !):


 The logical operators are the symbols that are used to combine multiple
conditions into one condition.

 The following table provides information about logical operators.


Operator Meaning Example
Logical AND - Returns TRUE if all conditions are
&& 10 < 5 && 12 > 10 is FALSE
TRUE otherwise returns FALSE
Logical OR - Returns FALSE if all conditions are
|| 10 < 5 || 12 > 10 is TRUE
FALSE otherwise returns TRUE
Logical NOT - Returns TRUE if condition is FLASE
! !(10 < 5 && 12 > 10) is TRUE
and returns FALSE if it is TRUE
Logical AND - Returns TRUE only if all conditions are TRUE, if any of the
conditions is FALSE then complete condition becomes FALSE.
 Logical OR - Returns FALSE only if all conditions are FALSE, if any of the
conditions is TRUE then complete condition becomes TRUE.
Example: C Program for illustration of logical operators

//Logical Operators
int main()
{
int a=32; //>=35 and(&&) <=100
printf("\nLogical And : %d",(a>=35 && a<=100));
printf("\nLogical Or : %d",(a>=35 || a<=100));
printf("\nLogical Not : %d",!(a>=35));
return 0;
}
Output: Logical And : 0
Logical Or : 1
Logical Not : 1
4. Increment & Decrement Operators (++ & --)
 The increment and decrement operators are called unary operators because
both need only one operand.
 The increment operator adds one to the existing value of the operand and the
decrement operator subtracts one from the existing value of the operand.
 C has two special unary operators called increment (++) and
decrement (--) operators.
 Unary Increment Operator, denoted by "++"
 Unary Decrement Operator, denoted by "--"

 These operators increment and decrement value of a variable by 1.


 The increment and decrement operators are used in-front of the operand (++a)
or after the operand (a++).
 If it is used in-front of the operand, we call it as pre-increment or pre-
decrement and if it is used after the operand, we call it as post-
increment or post-decrement.

 Pre-Increment or Pre-Decrement: In the case of pre-increment, the value of


the variable is increased by one before the expression evaluation. In the case of
pre-decrement, the value of the variable is decreased by one before the
expression evaluation. That means, when we use pre-increment or pre-
decrement, first the value of the variable is incremented or decremented by one,
then the modified value is used in the expression evaluation.
Example: C Program for pre increment operator
#include<stdio.h>
#include<conio.h>
void main()
{
int i = 5,j;
j = ++i; // Pre-Increment
printf("i = %d, j = %d",i,j);
}
Output: i = 6, j = 6

 Post-Increment or Post-Decrement: In the case of post-increment, the value


of the variable is increased by one after the expression evaluation. In the case
of post-decrement, the value of the variable is decreased by one after the
expression evaluation. That means, when we use post-increment or post-
decrement, first the expression is evaluated with existing value, then the value
of the variable is incremented or decremented by one.
 Example: C Program for post increment operator
#include<stdio.h>
#include<conio.h>
void main()
{
int i = 5,j;
j = i++; // Post-Increment
printf("i = %d, j = %d",i,j);

}
Output: i = 6, j = 5
5. Assignment Operators (=, +=, -=, *=, /=, %=)
 The assignment operators are used to assign right-hand side value (Rvalue) to
the left-hand side variable (Lvalue).

 The assignment operator is used in different variants along with arithmetic


operators.

 The following table describes all the assignment operators in the C


programming language.

Example: C Program for assignment operator


//Assignment operator

int main()
{
int a=10,b=5; Output : A : 15
//+= A : 5
a+=b; //a=a+5
printf("A : %d",a); //15
a-=10; //a=a-10
printf("\nA : %d",a);
return 0;
}

6. Bitwise Operators (&, |, ^, ~, >>, <<)


 The bitwise operators are used to perform bit-level operations in the c
programming language.
 When we use the bitwise operators, the operations are performed based on the
binary values.
 The following table describes all the bitwise operators in the C programming
language.
 Let us consider two variables A and B as A = 25 (11001) and B = 20 (10100).

Operator Meaning Example


the result of Bitwise AND is 1 if all the A&B
& (Bitwise AND) ⇒ 16 (10000)
bits are 1 otherwise it is 0
the result of Bitwise OR is 0 if all the A|B
| (Bitwise OR) ⇒ 29 (11101)
bits are 0 otherwise it is 1
the result of Bitwise XOR is 0 if all the A^B
^ (Bitwise XOR) ⇒ 13 (01101)
bits are same otherwise it is 1
the result of Bitwise once complement ~A
~ (Bitwise NOT) ⇒ 6 (00110)
is negation of the bit (Flipping)
the Bitwise left shift operator shifts all
A << 2
<< (Left Shift) the bits to the left by the specified
⇒ 100 (1100100)
number of positions
the Bitwise right shift operator shifts
A >> 2
>> (Right Shift) all the bits to the right by the specified
⇒ 6 (00110)
number of positions

Example: C Program to illustrate Bitwise operators


//Bitwise Operators
int main()
{ Output
int a=25,b=45,c; Bitwise And : 9
printf("\n Bitwise And : %d",a&b);
printf("\n Bitwise Or : %d",a|b); Bitwise Or : 61
printf("\n Bitwise Xor : %d",a^b);
Bitwise Xor : 52
printf("\n Bitwise Not : %d",~a);
a=16; Bitwise Not : -26
b=a<<2;
c=a>>2; Left Shift : 64
printf("\n Left Shift : %d",b); Right Shift : 4
printf("\n Right Shift : %d",c);
return 0;
}

7. Conditional Operator (? :)
 The conditional operator is also called a ternary operator because it requires
three operands.
 This operator is used for decision making. In this operator, first we verify a
condition, and then we perform one operation out of the two operations based on
the condition result.
 If the condition is TRUE the first option is performed, if the condition is FALSE the
second option is performed.
 The conditional operator is used with the following syntax.

Condition ? TRUE Part : FALSE Part;

Example: A = (10<15)?100:200; ⇒ A value is 100


Fig: Illustration of Conditional operator

Example: C Program for illustration of condition operator

1. // conditional operator
2. #include <stdio.h>
3. #include <conio.h>
4. int main()
5. {
6. int age; // variable declaration
clrscr();
7. printf("Enter your age");
8. scanf("%d",&age); // taking user input for age variable
9. (age>=18)? (printf("Eligible for voting")) : (printf("Not eligible for voting"));
10. return 0;
11. }
Output: Enter your age 12
Not eligible for voting
Enter your age 21
Eligible for voting

Example 2: C program to check whether the given number is even or odd using
conditional operator
#include <stdio.h>
int main()
{
int number;
printf(“\n Enter the number”);
scanf(“%d”,&number);
(number % 2 == 0) ? printf("Even Number") : printf("Odd Number");
return 0;
}
Output: Enter the number 5
Odd number
8. Special Operators (sizeof, pointer, comma, dot, etc.)
The following are the special operators in c programming language.

 sizeof operator
This operator is used to find the size of the memory (in bytes) allocated for a variable.
This operator is used with the following syntax.

Syntax: sizeof (variableName);

Example: sizeof(A); ⇒ the result is 2 if A is an integer

 Pointer operator (*)


This operator is used to define pointer variables in c programming language.

 Comma operator (,)


This operator is used to separate variables while they are declaring, separate the
expressions in function calls, etc.

 Dot operator (.)


This operator is used to access members of structure or union.
C - Expressions

What is an expression?
An expression is a collection of operators and operands that represents a specific
value.

 In the above definition, an operator is a symbol that performs tasks like


arithmetic operations, logical operations, and conditional operations, etc.
 Operands are the values on which the operators perform the task. Here operand
can be a direct value or variable or address of memory location.

Expression Types in C
In the C programming language, expressions are divided into THREE types. They are as
follows...

 Infix Expression
 Postfix Expression
 Prefix Expression

The above classification is based on the operator position in the expression.

Infix Expression
The expression in which the operator is used between operands is called infix
expression.
The infix expression has the following general structure.

Operand1 Operator Operand2

Postfix Expression
The expression in which the operator is used after operands is called postfix expression.
The postfix expression has the following general structure.

Operand1 Operand2 Operator


Prefix Expression
The expression in which the operator is used before operands is called a prefix
expression.
The prefix expression has the following general structure.

Operator Operand1 Operand2


C Operator Precedence and Associativity
What is Operator Precedence?
Operator precedence is used to determine the order of operators evaluated in an
expression. In c programming language every operator has precedence (priority). When
there is more than one operator in an expression the operator with higher precedence is
evaluated first and the operator with the least precedence is evaluated last.

What is Operator Associativity?


Operator associativity is used to determine the order of operators with equal precedence
evaluated in an expression. In the c programming language, when an expression
contains multiple operators with equal precedence, we use associativity to determine the
order of evaluation of those operators.

In c programming language the operator precedence and associativity are as shown in the
following table.

Introduction to Expression Evaluation in C

While knowing about expression evaluation we must understand what is an expression


in C and what is an expression means. An expression in C is defined as 2 or more
operands are connected by one operator and which can also be said to a formula to
perform any operation. An operand is a function reference, an array element, a variable,
or any constant. An operator is symbols like “+”, “-“, “/”, “*” etc. Now expression
evaluation is nothing but operator precedence and associativity. Expression precedence
in C tells you which operator is performed first, next, and so on in an expression with
more than one operator with different precedence. This plays a crucial role while we are
performing day to day arithmetic operations. If we get 2 same precedences appear in an
expression, then it is said to be “Associativity”. Now in this case we can calculate this
statement either from Left to right or right to left because this both are having the same
precedence.

Types of Expression Evaluation in C

In C there are 4 types of expressions evaluations

1. Arithmetic expressions evaluation

2. Relational expressions evaluation

3. Logical expressions evaluation

4. Conditional expressions evaluation

1. Arithmetic expression Evaluation


Addition (+), Subtraction(-), Multiplication(*), Division(/), Modulus(%), Increment(++) and
Decrement(–) operators are said to “Arithmetic expressions”. These operators work in
between operands. like A+B, A-B, A–, A++ etc. While we perform the operation with these
operators based on specified precedence order as like expression.

A+B*C/D-E%F

Program:
//used to include basic C libraries
#include <stdio.h>
#include <conio.h>
//main method for run c application
int main()
{
//declaring variables
int a,b,result_art_eval;
clrscr();
//Asking the user to enter 2 numbers
printf("Enter 2 numbers for Arithmetic evaluation operation\n");
//Storing 2 numbers in varaibles a and b
scanf("%d\n%d",&a,&b);
//Arithmetic evaluation operations and its result displaying
result_art_eval = a+b*a/b-a%b;
printf("================ARITHMETIC EXPRESSION EVALUATION==============\n");
printf("Arithmetic expression evaluation of %d and %d is = %d \n",a,b,result_art_eval);
printf("=========================================================");
return 0;
}
2. Relational expression evaluation

== (equal to), != (not equal to), > (greater than), < (less than), >= (greater than or equal
to), <= (less than or equal to) operators are said to “Relational expressions”. This
operator works in between operands. Used for comparing purpose. Like A==B, A!=B,
A>B, A<B etc. While we perform the operation with these operators based on specified
precedence order:

A==B || A!=B||A<B||A>B;

C-Program:
//used to include basic C libraries
#include <stdio.h>
//main method for run c application
int main()
{
//declaring variables
int a,b;
int result_rel_eval;
//Asking the user to enter 2 numbers
printf("Enter 2 numbers for Relational evaluation operation\n");
//Storing 2 numbers in varaibles a and b
scanf("%d\n%d",&a,&b);
//Relational evaluation operations and its result displaying
//If we get result as 1 means the value is true and if it is 0 then value is false in C
result_rel_eval = (a<b||a<=b||a>=b||a>b||a!=b);
printf("================RELATIONAL EXPRESSION EVALUATION==============\n");
if(result_rel_eval==1)
{
printf("Relational expression evaluation of %d and %d is = %d \n",a,b,result_rel_eval);
}
else
{
printf("Relational expression evaluation of %d and %d is = %d \n",a,b,result_rel_eval);
}
printf("===============================================================");
return 0;

3. Logical expression evaluation


&&(Logical and), ||(Logical or) and !(Logical not) operators are said to “Logical
expressions”. Used to perform a logical operation. These operators work in between
operands. Like A&&B, A||B, A!B etc. While we perform the operation with these
operators based on specified precedence order:

A&&B||B!A;
C-Program:
#include <stdio.h>
int main()
{
//declaring variables
int a,b;
int result_log_eval;
//Asking the user to enter 2 numbers
printf("Enter 2 numbers for Logical evaluation operation\n");
//Storing 2 numbers in varaibles a and b
scanf("%d\n%d",&a,&b);
//Logical evaluation operations and its result displaying
//If we get result as 1 means the value is true and if it is 0 then value is false in C
result_log_eval = (a||b&&a);
printf("================LOGICAL EXPRESSION EVALUATION==============\n");
if(result_log_eval==1)
{
printf("Logical expression evaluation of %d and %d is = %d \n",a,b,result_log_eval);
}
else
{
printf("Logical expression evaluation of %d and %d is = %d \n",a,b,result_log_eval);
}
printf("===============================================================");
return 0;
}

4. Conditional expression Evaluation


?(Question mark) and :(colon) are said to “Conditional expressions”. Used to perform a
conditional check. It has 3 expressions first expression is condition. If it is true then
execute expression2 and if it is false then execute expression3. Like (A>B)?”A is Big”:”B
is Big”. While we perform the operation with these operators based on specified
precedence order

(X+2=10)?’true’:’false’;
C-Program:

//used to include basic C libraries


#include <stdio.h>
//main method for run c application
int main()
{
//declaring variables
int a,b,c;
int result_con_eval;
//Asking the user to enter 3 numbers
printf("Enter 3 numbers for Conditional evaluation operation\n");
//Storing 3 numbers in varaibles a, b and c
scanf("%d\n%d\n%d",&a,&b,&c);
//Conditional evaluation operations and its result displaying
result_con_eval=(a>b && a>b)? a: (b>a && b>c)? b:c;
printf("================CONDITIONAL EXPRESSION EVALUATION==============\n");
printf("Maximum value of %d, %d and %d is = %d \n",a,b,c,result_con_eval);
printf("===============================================================");
return 0;
}
Type Casting and Conversion in C

In a programming language, the expression contains data values of the same data type
or different data types. When the expression contains similar data type values then it is
evaluated without any problem. But if the expression contains two or more different data
type values then they must be converted to the single data type of destination data type.
Here, the destination is the location where the final result of that expression is stored.
For example, the multiplication of an integer data value with the float data value and
storing the result into a float variable. In this case, the integer value must be converted
to float value so that the final result is a float data type value.

In a c programming language, the data conversion is performed in two different methods


as follows...

1. Type Conversion
2. Type Casting

Type Conversion
 The type conversion is the process of converting a data value from one data type to
another data type automatically by the compiler.
 The compiler does this automatic conversion at compile time.
 Sometimes type conversion is also called implicit type conversion.
 The implicit type conversion is automatically performed by the compiler.
 For example, in c programming language, when we assign an integer value to a
float variable the integer value automatically gets converted to float value by
adding decimal value 0.
 When a float value is assigned to an integer variable the float value automatically
gets converted to an integer value by removing the decimal value.

For type conversion to take place, the following two conditions must be followed:-

o The destination data type and source data type must be compatible. For example,
numeric types (like ‘int’ and ‘float’) are compatible, while numeric to char /
numeric to boolean / char to boolean is not compatible.
o The destination data type must be larger than the source data type. For example,
int can be converted to float, but float cannot be converted to int.
 To understand more about type conversion observe the following...

#include<stdio.h>
#include<conio.h>
void main(){
int i = 95 ; Output:
float x = 90.99 ;
char ch = 'A' ; i value is 90
i = x ;
printf("i value is %d\n",i); x value is 90.000000
x = i ;
printf("x value is %f\n",x);
i = ch ;
i value is 65
printf("i value is %d\n",i);

}
In the above program, we assign i = x, i.e., float variable value is assigned to the integer
variable. Here, the compiler automatically converts the float value (90.99) into integer
value (90) by removing the decimal part of the float value (90.99) and then it is assigned
to variable i. Similarly, when we assign x = i, the integer value (90) gets converted to
float value (90.000000) by adding zero as the decimal part.

Typecasting
 Typecasting is also called an explicit type conversion.
 Compiler converts data from one data type to another data type implicitly.
 When compiler converts implicitly, there may be a data loss.
 In such a case, we convert the data from one data type to another data type using
explicit type conversion.
 To perform this we use the unary cast operator.
 To convert data from one type to another type we specify the target data type in
parenthesis as a prefix to the data value that has to be converted.
 The general syntax of typecasting is as follows.

(TargetDatatype) DataValue

Example
int totalMarks = 450, maxMarks = 600 ;

float average ;

average = (float) totalMarks / maxMarks * 100 ;

In the above example code, both totalMarks and maxMarks are integer data values.
When we perform totalMarks / maxMarks the result is a float value, but the destination
(average) datatype is a float. So we use type casting to convert totalMarks and maxMarks
into float data type.

Example: C Program using Type casting

#include<stdio.h>
#include<conio.h> Output:
int main()
Enter the values of a, b
{ and c23
int a,b,c;
float avg; 34
printf("\n Enter the values of a, b and c"); 56
scanf("%d%d%d",&a,&b,&c);
avg = (a+b+c)/3; Average before type
printf("\n Average before type casting is %f", avg); casting is 37.000000
avg = (float)(a + b + c) / 3 ; Average after type casting
printf("\n Average after type casting is %f", avg); is 37.666668
return 0;
}
Type Conversion Vs Type Casting:

Type Conversion Type Casting


The compiler automatically converts a data The programmer converts a data type into
type into another data type. another data type.
Applicable only to compatible data types. Applicable to compatible data types as well
as incompatible data types.
No casting operator is required. Casting operator () is used to cast a data
type to another data type.
The source data type with a smaller size is The source data type with a larger size is
converted into the destination data type converted into the destination data type
with a larger size. with a smaller size.
It takes place during the compile time. It takes place when the programmer writes
the code.
No chance of data loss. The chance of data loss is high.
Less efficient and reliable as information More efficient and reliable.
like signs can be lost (when a signed type
is implicitly converted to an unsigned type),
or overflow can happen (when long long is
implicitly converted to float).
Also called Widening Type Conversion/ Also called narrowing conversion/ Explicit
Implicit Conversion/ Casting Down. Conversion/ Casting Up.
Example: int i = 20;float f = i; Example: float f = 10.0;int i = (int) f;

You might also like