Sei sulla pagina 1di 20

CO-I

Session-1&2 Introduction to Algorithms and Flow charts


Content:
Necessity of Programming: Now a days the usage of computers are increased in most of the fields, need to
develop applications to interact with them. For example washing machines, TVs, refrigerators, pcs, calculators,
cell phones etc. Everything is working based on software. So that there is an emerging need to know about
programming that leads to development of such kind of applications.
ALGORITHMS AND FLOWCHARTS
Definitions
Algorithm: - An algorithm is the step by step procedure of solution of a problem.
Flow chart: - A flow chart is a pictorial representation of an algorithm.
Characteristics of good Algorithms:
1. Each step in an algorithm should be precise and unambiguous.
2. Each step should be executed in a finite amount of time.
3. The algorithm should work on all legitimate inputs.
4. The required output should be obtained after the algorithm ends.
Algorithms for few example problems
Q1. Write an algorithm to find the area of a circle?
Ans. Algorithm:
1. Start
2. A,R are variables
3. Read R value from the user
4. A3.14*R*R
5. Print the value of variable A
6. Stop
Q2. Write an algorithm to find the area of a rectangle?
Ans. Algorithm:
1. Start
2. L,B,A are variables
3. Read L,B values from the user
4. A L*B
5. Print the value of variable A
6. Stop.
Q3. Write an algorithm to find the given number is even or odd?
Ans. Algorithm:
1. Start
2. N is a variable
3. Read N value from the user
4. If N%2 == 0 then
Print “given number N is EVEN”.
Else
Print “given number N is ODD”
5. Stop.
Q4. Write an algorithm to find biggest of given two numbers?
Ans. Algorithm:
1. Start
2. N1, N2 are two variables.
3. Read N1, N2 values from the user.
4. If N1> N2 then
Print “N1 is bigger number”.
Else If N2> N1 then
Print “N2 is bigger number”.
Else
Print “both are equal”.
5. Stop.
Q5. Write an algorithm to find the biggest of given 3 distinct numbers?
Ans. Algorithm:
1. Start.
2. A, B, C are three variables.
3. Read values from the user to A, B, C variables.
4. If A>B and A>C then
Print A value.
Else If B>C and B>A then
Print B value.
Else
Print C value.
5. Stop.
Q6. Write an algorithm to find the sum of first N natural numbers?
Ans. Algorithm1:
1. Start.
2. S, N are variables.
3. Read N value from the user.
4. S  N*( N+1)/2.
5. Print the value of S.
6. Stop.
Algorithm2:
1. Start
2. S, N, I are variables. // S – to store final sum value, N- to store boundary
value, I-to store loop index value
3. Read N value from the user.
4. S=0. //initially total sum is zero so that initialize S with 0.
5. I = 0 // initially I value is zero
6. If I <= N then
S = S + I.
I = I + 1.
goto step 6.
7. Print the value of S.
8. Stop.

Session-3 Introduction to C Programming Language


Content:
History of C
C is a programming language developed at AT&T’s bell laboratories of USA in 1972. It was designed and
written by a man named DENNIS RITCHIE. In the late seventies c began to replace the more familiar languages
of that time like PL\I(Programming Language One", pronounced "pee-el-one"),ALGOL etc. By 1960,many
programming languages came into existence, almost each for a specific purpose for example COBOL was
being used for commercial or business applications, FORTRAN for scientific applications and so on .So, people
started thinking why could not there be a one general purpose language .Therefore ,an International Committee
was set up to develop such a language ,which came out with the invention of ALGOL60,but this language
never became popular because it was too abstract and too general. To improve this, new language called
combined programming language (CPL) was developed at Cambridge University. But this language was very
complex in the sense that it has too many features and it was very difficult to learn. Matrin Richards at
Cambridge University reduced the features of CPL and developed a new language called BCPL (Basic
Combined Programming Language) but unfortunately it turned out to be much less powerful and too specific.
Ken Thompson at AT & T’s bell labs, developed a language called B, but like BCPL this was also too specific.
Ritchie inherited the features of B and BCPL and added some features on his own and developed a language
called C. C proved to be quite compact and coherent.
Features of C
i) Middle Level Language: Among the two types of programming languages discussed
earlier(High Level and Low level), C lies in between these two categories. That’s why it is often
called a middle level language, since it was designed to have both: relatively good programming
efficiency and relatively good machine efficiency.
ii) Portability: C code is very portable, that it allows the same C program to be run on the machines
with different hardware configurations.
iii) Flexibility: The flexibility of C allows it to be used for systems programming as well as for
application programming.
iv) Structured Language: C is commonly called a structured language because of structural
similarities of ALGOL and PASCAL. Structured language is one that divides the entire program
into the modules using top-down approach where each module executes one job or task. It is easy
for debugging, testing and maintenance if a language is structured one.
STRUCTURE OF A C PROGRAM
C is a case sensitive language. All c programs consist of one or more functions. One function that must be
present in every C program is main(). This is the first function called up when the program execution begins.
Basically main () outlines what a program does. The structure of a c program is illustrated in flowing
figure1.1.Where functions fun1 (), fun2 () represent user defined functions

INPUT FUNCTION- scanf()


We can assign values to variable through assignment statements such as x = 5 ,a = 0 and also can read values
from keyboard by using scanf() function. The general form of scanf() is as follows:

scanf(“control string”,&variable1,&variable2,….);

The control string contains format of the data being received. The ampersand symbol (&)before each variable
name is the operator that specifies variable name’s address. The use of & is must in scanf() function.
Ex: scanf(”%d”,&x);
When this statement is encountered, the execution of program stops and waits for the value of the variable x to
be typed in .The format %d specifies that an integer value is to be read from the terminal, the user has to type
the value in integer form. Once number typed and return key pressed, the next statement in the program is
executed.
Commonly used format specifications:
%c – read a single character.
%d – read a decimal Integer.
%e – read a floating point value in exponential form.
%f – read a floating point value.
%i – read a decimal, hexadecimal or octal Integer.
%h– read a short integer.
%x – read a hexadecimal integer (unsigned) using lower case a – f.
%X – read hexadecimal integer (unsigned) using upper case A – F.
%o – read an octal integer.
%s – read a string
%u –read unsigned decimal integer.
OUTPUT FUNCTION-printf()
printf() function in ‘C’ allows us to display output on console. Output data can be written from computer to
standard output device such as monitor. The general form of printf() is as follows

printf(“control string”,exp1,exp2,exp3,……);
The control string contains format of the data to be displayed and exp1, exp2, exp3…are output expressions.
The function accepts a series of arguments, each applying to a conversion specifier in the given control string,
printf() prints the formatted information to the standard output device, usually the display screen.

Session-4 compilers, interpreters and Tokens


Content:
COMPILER vs INTERPRETER:
• A compiler is a special type of program that transforms source code written in a programming
language (the source language) into machine language comprising of just two digits- 1s and 0s (the
target language). The resultant code in 1s and 0s is known as the object code. The object code is the
one which will be used to create an executable program.
• If the source code contains errors then the compiler will not be able to its intended task. Errors that
limit the compiler in understanding a program are called syntax errors. Syntax errors are like spelling
mistakes, typing mistakes, etc. Another type of error is logic error which occurs when the program
does not function accurately. Logic errors are much harder to locate and correct.
• Interpreter: Like the compiler, the interpreter also executes instructions written in a high-level
language.
While the compiler translates instructions written in high level programming language directly into the machine
language; the interpreter on the other hand, translates the instructions into an intermediate form, which it then
executes.

Character Set Of ‘C’ Programming Language:-


Like all languages, ‘C’ programming language also uses a finite set of symbols as its character set
(alphabet set). They are
a. All upper case and lower case English letters
b. 0 to 9 digits
c. White spaces( single white space, horizontal tab space, vertical tab space, carriage return, form feed
and new line space, )
d. Special symbols { ~, `, !, @, #, $, %, ^, &, *, (, ), _, -, +, =,|,\, }, ], {, [, :, ;, “, ‘ , ?, /, >, < , ,, ., }

Token:- A Token is a smallest unit in a ‘C’ Program, which is similar to a word in the natural language text.
In ‘C’ Language these tokens are classified into following categories.
a. Keywords
b. Identifiers
c. Constants
d. White spaces
e. Operators

Keywords:- Keywords are one special type of tokens in ‘C’ Language, where each keyword will indicate
a specific task. ‘C’ Language provides the following list of 32 Keywords, each indicates a specific task. These
keywords are similar to the verbs in Natural languages. The task for every keyword is defined by the compiler
developer at the time of compiler development. The definition of every keyword will not be able to change by
the programmer or user. These are fixed.
Keyword list:-
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
Along with these keywords the following additional keywords are supported by the Turbo-C and Borland-
C compilers.
asm far interrupt pascal near huge cdecl
Identifier:-
In C programming, identifiers are names given to C entities, such as variables, functions, structures,
etc. identifiers are created to give unique name to C entities to identify it during the execution of the
program.
Rules to create an identifier in ‘C’ program:-
a. An identifier should contains only letters, digits and underscore symbol (_).
b. A keyword is not used as an identifier.
c. The first character in an identifier should be a letter or underscore (_) but not digit.

Ex: int x23_fsa;


int _sdfsa;
float _999fsal;
Constants:-
Constants are the terms that can’t be changed during the execution of a program. For example 5, 6,
3.454, ‘a’, ‘L’, “hello” ext . All constants in ‘C’ language are classified as follows.
a. Integer constants
b. Floating-point constants
c. Character constants
d. String constants

Integer constants:-
Integer constants are the numeric constants without any fractional part or exponential part. In ‘C’
Language we can represent integer constants in different number systems. 1. Decimal system 2. Octal
system 3. Hexadecimal system.
Note:
 Every octal number in ‘C’ program will preceded by 0(zero).
 Every hexadecimal number in ‘C’ program will preceded by 0x or 0X as shown in the following
examples.
 Examples;
Decimal constants -- 99, -88, 123, etc.
Octal constants -- 04334, 0453, etc..
Hexadecimal constants -- 0x23 , 0X23, 0x34ab4.
Example:
#include<stdio.h>
void main()
{
int x = 0123;
int y = 012;
printf(“%d”,x+y);
}

The output of this program 93, because here x, y are initialized with octal constants. The sum of x, y
value will be converted into decimal number by “%d “ in printf() statement and then print on output device. If
we use “%o” instead of “%d” then it prints octal equivalent number of x+y (i.e 135) on output device.

Floating-point constants:-
Floating point constants are the numeric constants that have either fractional form or exponent form.
Exponent form is called as scientific notation. For example
Ex: float x = 3.14159;
float x = 314.159E-2;
float y = 0.0314159E+2;
NOTE:-
1. The general form for scientific notation is
Mantissa e
exponent

2. The mantissa is either a real number or an integer.


3. The exponent is an integer number with an optional plus sign or minus sign.
4. Here e will indicate the exponent. We can use either uppercase E or lowercase e letter.
5. Embedded white space is not allowed.

Character constants:-
If any ‘C’ alphabet is enclosed with 2 single quotes then it is called character constant in ‘C’ language.
Example:-
‘5’ , ‘a’, ‘A’, ‘ ‘, ….etc
Character constants have integer values known as ASCII values.
Example:
printf(“%d”,’B’);
It prints the 66. This 66 is the ASCII value of character ‘B’.
Every character in ‘C’ Language will contains a ASCII value, so that we can use ‘C’ character in
asthmatic operations.
1. Write a program to print all ASCII value of all characters.
#include<stdio.h>
void main()
{
int i=0;
for(i=0;i<256;i++)
{
printf(“\n%d ---- %c\n”,i,i);
}
}

String Constants:-
If a sequence of characters are enclosed with in double quotes then that is treated as string constant in
‘C’ Language. For example
“hello”, “123”, “x”, “1”, “23+23*45”.
Backslash Character Constants:-
‘C’ language provides few special backslash character constants, which are used in output functions.
For example a symbol ‘\t’ stands for tab space character. These backslash character constants are also known
as escape sequences. The following list of backslash characters are supported by ‘C’ programming language
to indicate specific individual task.
S.NO Constants Meaning
1 ‘\a’ Alert bell( beep sound)
2 ‘\b’ Back space
3 ‘\f’ Form feed
4 ‘\n’ New line
5 ‘\r’ Carriage return
6 ‘\t’ Horizontal tab
7 ‘\v’ Vertical tab
8 ‘\’’ Prints the Single quote on output device
9 ‘\” ’ Prints the Double quote on output device
10 ‘\?’ Prints the question mark on output device
11 ‘\\’ Prints the backslash on output device
12 ‘\0’ Null character
Variables:
Variables are memory locations in computer’s memory to store data. To indicate the memory location,
each variable should be given a unique name called identifier. Variable names are just the symbolic
representation of a memory location.
Example: sum, car_no, r_number, count etc.
Syntax for variable declaration statement in ‘C’:
Data_type identifier[,[=constants]identifier];
Example: int x, marks;
int x = 5, marks = 56;
Rules for writing variable names in C
1. Variable name can be composed of letters( both uppercase and lowercase letters), digits and
underscore(_) only.
2. The first letter of a variable should be either a letter or an underscore. But it is discouraged to start
variable name with an underscore though it is legal. It is because, variable name that starts with
underscore can conflict with system names and compiler may complain.
3. There is no rule for the length of a variable. However, the first 31 characters of a variable are
discriminated by the compiler. So, the first 31 letters of two variables in a program should be different.

NOTE:- In C programming, you have to declare variable before using it in the program.

Session-5 Data Types


Content:
DATA TYPES
C language provides a rich set of data types. In C language these data types are classified as:
1. Primary data types ( or Fundamental data types or Basic data types or Built-in data types).
2. User defined data types
3. Derived data types.
Primary data types:-
Primary data types are those which are already available in C compiler. These are defined by the
compiler developer. These primary data types are classified into two categories based on the type of data. They
are i. Integral data ii. Floating-point data. Once again this data is classified as shown in the following tree
hierarchy structure.
Based on the size of the floating point data once again it is classified into 3 types of data. i) Floating-point data
type. ii) Double precision floating point data type. iii) Extended Double precision floating point data type.
PRIMARY DATA TYPES
INTEGRAL DATA TYPE
Integer data type Character data type
Signed data Unsigned data Signed character data
Integer data type Unsigned integer data type type
Short integer data type Unsigned short integer data type Unsigned character
Long integer data type Unsigned long integer data type data type

FLOATING-POINT DATA TYPE


Floating point data type Double precision floating-point Extended double precision
data type floating-point data type

Integers are whole numbers with a range of values supported by a particular machine. Generally,
integers occupy one word of storage, and since the word sizes of machines vary (like 16-bit processor or 32-
bit processor) the size of integer that can be stored depends on the computer. If we use a 16-bit word length,
the size of the integer is 2 bytes. If we use a 32-bit processor then the size of the integer is 4 bytes. Size and
ranges of different basic data types in C language are given in the following table.

DATA TYPE SIZE RANGE KEYWORD


Signed character data type 1 byte -128 to 127 char / signed char
Unsigned character data type 1 byte 0 to 255 unsigned char
Signed short integer data type 1 byte -128 to 127 signed short int / short int / short
Unsigned short integer data type 1 byte 0 to 255 unsigned short int / unsigned short
Signed integer data type 2 bytes -215 to 215-1 signed int / int
Unsigned integer data type 2 bytes 0 to 216-1 unsigned int / unsigned
Signed long integer data type 4 bytes -231 to 231-1 signed long int / long int / long
Unsigned long integer data type 4 bytes 0 to 232-1 unsigned long int / unsigned long
Floating point data type 4 bytes 3.4E-38 to Float
3.4E+38
Double precision floating point 8 bytes 1.7E-308 to Double
data type 1.7E+308
Extended double precision 10 bytes 3.4E-4932 to long double
floating point data type 1.1E+4932

Floating point numbers (real numbers) are stored in 32 bits( in all 16-bit and 32-bit machines), with 6 digits of
precision. When the accuracy provided by a float number is not sufficient then double can be used. A double
data type numbers uses 64 bits giving a precision of 14 digits.

Session-6 Pointers
Content:
Definition:Pointer is a variable that store the address of another variable.

Relationship between variables and pointers


If x is a variable and ptr_variable is a pointer variable then
ptr_variable=&x ( & is a unary address operator)

DECLARATION OF POINTER VARIABLES


Example :Declaration Interpretation
Program to illustrate pointer declaration
#include<stdio.h>
#include<conio.h>
main()
{
int *ptr;
int sum;
sum=45;
ptr=&sum;
printf (“\n The value represented by the variable sum is %d”, sum);
printf (“\n The value pointed by the pointer variable ptr is %d”, *ptr);
}
The variable name ‘sum’ refer the data item stored in the memory location allocated to sum.That data iem
can also be refered through the pointer variable ‘ptr’. Hence first and second printf statements will result in the
same output.
Example: Program to display the contents of the variable their address using pointer variable
#include <stdio.h>
main()
{
int num, *intptr;
float x, *floptr;
char ch, *cptr;
num=123;
x=12.34;
ch=’a’;
intptr=&num;
cptr=&ch;
floptr=&x;
printf(“Num %d stored at address %u\n”,*intptr,intptr);
printf(“Value %f stored at address %u\n”,*floptr,floptr);
printf(“Character %c stored at address %u \n”,*cptr,cptr);
}
POINTER EXPRESSIONS &POINTER ARTHMETIC
Like any other variable, pointer variable can be used in arithmetic expressions.
For example if p1 and p2 are properly declared and initialized pointers, then the following statements are
valid.
y = *p1 * *p2;
sum = sum + *p1;
z = 5 - *p2/p1;
*p2 = *p2 + 10;
x=3+5/ *p1;
Note that there must be a gap between / and *,otherwise /* is taken as the beginning of a comment.
Increment and decrement operations can be applied on pointers. The expressions ++p1,--p2 etc are
allowed.
Example:Program to illustrate the pointer expressions
#include <stdio.h>
main()
{
int ptr1,ptr2;
int a,b,x,y,z;
a=30;b=6;
ptr1=&a; ptr2=&b;
x=*ptr1+ *ptr2 –6;
y=6*- *ptr1/ *ptr2 +30;
printf(“\nAddress of a is %u”,ptr1);
printf(“\nAddress of b is %u”,ptr2);
printf(“\na=%d, b=%d”,a,b);
printf(“\nx=%d,y=%d”,x,y);
ptr1=ptr1 + 70;
ptr2= ptr1;
printf(“\na=%d, b=%d”,a,b);
}
Pointer Arithmetic
The following operations can be performed on pointers:
1. An integer constant or variable can be added to a pointer or subtracted from the pointer.
int x,*p1,i;
p1=&x;
the expressions such as p1+1,p1+3,p1+i,
p1-1,p1-2,p1-i are allowed.
2. A pointer can be incremented or decremented.
The expressions such as ++p1,--p1,p1-- etc. are allowed.
3. Two pointers can be compared, if they are pointers to same datatype.
int *p1,*p2;
the expressions such as p1==p2,p1!=p2,p1<p2 are allowed.
4. One pointer can be subtracted from another pointer if both point to the same array.
int a[10],*p1,*p2;
p1=&a[0];
p2=&a[4];
k=p2-p1; is allowed
the value assigned to k is 4.
The following operations can’t be applied on pointers:
1. Addition of two pointers
2. Subtraction of one pointer from another pointer when they do not point to the same array
3. Multiplication of two pointers
4. Division of one pointer by another pointer
The expressions such as p1+p2,p1*p2,p1/p2,p1/3 are not allowed

Session-7 Files
Content:
A file is some reserved space on the disk where a group of related data is stored permanently in the system.
FILE OPERATIONS
The different basic file operations are
Naming a file
Creating / Opening a file
Closing a file
Writing data to a file
Reading data from a file
Appending a file
C supports a number of functions that have the ability to perform basic file operations, which includes:

Creating a new file / Opening an existing file


To create a new file or to open an existing file the function fopen( ) is used.
fopen( ) is a file function used to create a new file or to open an existing file. Its general form is

fp = fopen ( “filename”, “mode” );


where
fp – is a file pointer which is of structure data type FILE defind in stdio.h
The general syntax to declare the file pointer is

FILE *file-pointer;

For example,
FILE *p1, *p2, *fp;
“filename” – is the name of the file and is a string of characters that make up a valid filename for the
operating system. It may contain two parts, a primary name and an optional period with the extension.
For example,
“input.data”
“STUDENT.DAT”
“RESULTS.OUT”
“mode” – specifies the purpose of opening the file. The mode of the file may be one of the following
“w” -- open a new file for writing data
“r” -- open an existing file for reading data
“a” -- open an existing file for appending data to it
“r+” -- open an existing file for both reading and writing data
“w+” -- same as “w” except both for reading and writing
“a+” -- same as “a” except both for reading and appending

Closing a file
A file must be closed as soon as all operations on it have been completed. The function fclose() is used to
close the file that has been opened earlier.
fclose( ) is the counterpart of fopen( ). Closing file means delinking the file from the program and saving
the contents of the file. Its general form is
fclose(fp);

This would close the file associated with the file pointer fp.
fprintf( ) :The function is used to write multiple data items which may (or may not) be of different
types to a file. Its general form is.

fprintf( fp,“control-string”, arg1, arg2, arg3,…);

Where fp is a pointer to the file, “control-string” contains output specifications for the data to be written
and arg1, arg2 … are the arguments list. The function writes the data values of arg1, arg2… to the file
pointed by fp.

fscanf( ) :- This function is used to read multiple data items which may be of different types from a
file. Its general form is

fscanf( fp,“control-string”, v1, v2, v3,…);

The function reads data values in a given format from the file pointed by fp and returns the data values,
which are collected by the variable list.

Session-8 &9 Operators


Content:
C Language provides a rich set of operators to perform different basic operations on data (operands). Based on
the operations performed by the operators, they are classified into different groups as shown below.
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment and decrement operators
6. Conditional operators
7. Bitwise operators
8. Special operators

Arithmetic operators:
C Language provides a set of operators to perform few basic arithmetic operations, which are
described in the following table
s.no Operator symbol Meaning
1 + Addition operator or unary addition operator
2 - Subtraction operator or unary subtraction operator
3 * Multiplication operator
4 / Division operator
5 % Modulo division operator
 If any C expression having only arithmetic operators then we call it as arithmetic expression.
 If all operands of any arithmetic expression are integers then that arithmetic expression is called as
integer arithmetic expression
 If all operands of any arithmetic expression are real numbers then that arithmetic expression is called
as real arithmetic expression or floating point arithmetic expression.
 If any expression has different data type operand then we call that expression as mixed mode
arithmetic expression.
 Ex: void main()
{ int x=4,y=5;
float a,b;
a = 2.4;
b = 4.5;
printf(“\n%d”,x+y); integer arithmetic expression
printf(“\n%f”,a+b); floating point arithmetic expression
printf(“\n%f”,a+x); Mixed mode arithmetic expression
}
 An integer arithmetic expression always gives integers and a real arithmetic expression gives floating
value.
 We can use -,+,*,/ on any basic data type values, but % will not work on float or double data.
 Ex: void main()
{
float a=2.0,b=3.1;
a = a%b; this statement will gives an error.
}
 If number of operands of an operator is one then we call that operator as unary operator.
 If any operator takes two operands then we call that operator as binary operator.
 If 3 then we call it as ternary operator. In C language we have only one ternary operator.
 In integer division operation decimal part will truncate.
 During the integer division, if both operands are having the same sign then the result is truncated
towards the zero. If one of these two operands is negative then the direction of truncation is
implementation dependent.
 Ex: x = -3/5; here x is either 0 or -1
 During the modulo division the sign of the two operand are different then the result is always the sign
of the first operand
 Ex: X = -3%5; then x becomes -3.
X = 3%-5; then x becomes 3.

X = -3%-5; then x becomes -3.

Relational operators:-
C language provides six relational operators, which are used to compare the values of any two
variables or to compare the values of any two expressions. In C language all operators are binary operators.
The symbols which are used for relational operations and their meanings are described in the following table.
s.no Symbol Meaning of the operator Unary/binary Precedence Associativity
1 < Is less than Binary 1(high) Left-Right
2 > Is greater than Binary 1 Left-Right
3 <= Is less than or equal to Binary 1 Left-Right
4 >= Is greater than or equal to Binary 1 Left-Right
5 == Is equal to Binary 2 Left-Right
6 != Is not equal to binary 2(low) Left-Right
 Relational operators are having less precedence than all arithmetic operators.
 In relational operators <, >, <=, >= are having same precedence and similarly == , != are having same
precedence.
 <, <=, >, >= are having high precedence than ==, != operators.
 The expression in which we use only relational operators is called as Relational Expression.
 A relational expression can return either 0 or 1 i.e. either false or true.
 All relational operators are binary operators.

Logical operators:-
C language provides 3 basic logical operators which are used to connect two or more expressions.
Usually we use these operators in conditional statements to find the Boolean value of conditional expression.
The symbols and their meanings are shown in the following table.

s.no Symbol Meaning of the operator Unary/binary Precedence Associativity


1 && Logical AND Binary 2 Left-Right
2 || Logical OR Binary 3(least) Left-Right
3 ! Logical NOT Binary 1(high) Right-Left

Definitions:-
Op1 Op2 Op1 && Op2 Op1 || Op2 !Op1
Non-zero Non-zero 1 1 0
Non-zero Zero 0 1 0
Zero Zero 0 0 1
Zero Non-zero 0 1 1
Logical AND:- if both operands are non-zero values then only it returns 1 otherwise it returns 0.
Logical OR:- if both operands are zero values then only it returns zero otherwise it returns 1.
Logical NOT:- if the operand is non-zero value then it returns zero otherwise it returns 1

Conditional operator:
The operator symbol is ?: This is also called ternary operator. The conditional operator has three expressions.
The general form is
expression1?expression2:expresssion3

This is called conditional expression.


First, expression1 is evaluated, if the result is non-zero, the expression2 is evaluated and its value is the final
result. Otherwise, expression3 is evaluated and its value is the final result.

Example: To find the biggest of two numbers


big= (a>b)? a: b;
This is equivalent to the if –else statement
if (a>b)
big=a;
else
big=b;

Example: To check an integer is even or odd


(n%2)? printf (“Given integer is odd\n”): printf(“Given integer is even\n”);
This is equivalent to the statement
if(x%2)
printf(“given integer is odd\x”);
else
printf(“given integer is even\x”);

Example:To find absolute value of an expression


y=(x>=0)? x: -x;

Example: To evaluate the function defined by


F(x)= x2-x+1 of x>=0
2
x +x+1 of x<0
fx=(x>=0)?(x*x-x+1):(x*x+x+1);
Note:Conditional expression may be nested

Example: To find the biggest of three numbers


big=(a>b)?((a>c)?a:c):((b>c)?b:c);
Although conditional expression is nested, it is not recommended.

Increment and decrement operators(++ and--)


These two operators are unary operators. They exists in two forms i.e. pre and post(prefix and postfix)
i) Increment operator(++)
Increment operator is used to increment the value of its operand by 1.General form for pre incrimination is
++ operand
and post incrimination is

operand ++
where the operand must be a variable but cannot be constant or expression..++operand is called pre increment
or prefix increment and operand++ is called post increment or postfix increment
Example: pre incrementation
int i=20;
++i;
printf(“i=%d”,i);
output: i=21
Example: post incrementation
int i=20;
i++;
printf(i=%d”,i);
output:i=21;
In the above example prefix and postfix operation results in the same output. The prefix and postfix operations
differ in the value used for the operand when it is embedded inside expressions
Example: int x=10,y;
y=++x;
printf(“x=%d,y=%d”,x,y);
output: x=11,y=11
Here x value is incremented before it is assigned to y. So the expression y = ++x is equivalent to the two
expressions x=x+1 and y=x
Example: int a=5,b;
b=++a*4;
printf(“a=%d,b=%d”,a,b)
output: a=6,b=24
Example: int x=10,y;
y=x++;
printf(“x=%d,y=%d”);
output: x=11,y=10
Here value of x is incremented after it is assigned to y, thus the expression y=x++ is equivalent to the
expressions y=x and x=x+1;
Example: int a=5,b;
b=a++*4;
printf(“a=%d,b=%d”,a,b);
output: a=6,b=20

Note: ++4 and ++(x+y) are invalid expressions.

ii) Decrement operator ( - - )


This operator is used to decrement the value of the operand by 1.

General form is:

--operand
or
operand--

where the operand must be a variable but cannot be constant or expression.--operand is called pre decrement
or prefix decrement and operand-- is called post decrement or postfix decrement
Example:
int i=10;
--i;
printf(“i=%d”,i ) ;
output: i=9
Example: int i=10;
i--;
printf(“i=%d”,i);
output: i=9;
In the above example both the prefix and postfix operations results in the same value.

Example: int a=10,b;


b= -- a*3;
printf(“a=%d,b=%d\n”,a,b);
output: a=9,b=27
Example: int a=10,b;
b=a--*3;
printf(“a=%d,b=%d\n”,a,b);
output: a=9,b=30
Assignment Operators:
There are three forms of assignment: simple assignment, multiple assignment and compound (short
hand) assignment.

i) Simple assignment
The operator used is ‘=’.
The general form is

Variable name=expression;

The value of the expression is evaluated first and is assigned to the variable. The evaluation of the expression
is right to left.
Example:
x=10 a=10 && 5
y=12.5 a=x>y
a=”A”
area=0.5*b*h.
Note:
= is the assignment operator used to assign right side expression value to the left hand side variable.
= = is comparison operator to compare the value of left hand and right hand side expression.
a=b will assign b value to a
a==b will compare the values of a and b for equality.

ii) Multiple assignment


This is used to assign the value of an expression to two or more variables.

The general form is v1=v2=v3=expression;

The value of the expression is assigned to the variables v1, v2, v3 etc. the evaluation is right to left.
Example: a=b=0.
a=b=x+y
The value of x+y is assigned to b and then the value of b is assigned to a.

iii) Compound assignment


Compound assignment is a short hand notation for a simple assignment.The compound assignment
operators are
+ =, - =, * =, / =, % =.
To evaluate a compound assignment expression, first change it to a simple expression.

Compound assignment Equivalent simple expression


x+=expression x=x+expression
x-=expression x=x-expression
x*=expression x=x*expression
x/=expression x=x/expression
x%=expression x=x%expression

Example: a*=b+3 is evaluated as a=a*(b+3)


sum+=x is evaluated as sum=sum+x
a%=10 is evaluated as a=a%10.

Session-10 Expression Evaluation


Content:
Special operators:
The special operators are
i) comma operator(,)
ii) sizeof operator
iii) address operator(&),
iv) indirection operator(*)
v) cast operator

i) Comma operator
The comma operator is used to combine two more expressions into a single expression.
The general form is

expression1,expression2,---
,expressionN
The expression are evaluated from left to right and the value of the right most expression is the result of the
overall expression.
Example: int i=10,j;
j= ( i+=5, --i , i+20);
j is assigned the value 34.

Example: int m=5,n;


n=(m+=5,m%3);
n is assigned the value1.
Example: swapping of two integer variable using the comma operator
temp=a , a=b , b=temp;
The comma operator is most often used in for statement expressions to combine two or more expressions in
initial expression. And to combine increment or decrement in the third expression

Example: for(i=1 , j=10 ; i<j ; ++i , --j)


{
statements;
}
ii) size of operator
This operator is used to determine the number of bytes required to store a particular data type item in the
memory.
General form is
sizeof(operand)

where the operand may be name of the data type or constant or variable or expression.

Example: printf(“char size is %d bytes\n” , sizeof (char));


printf(“long int size is %dbytes\n” , sizeof(double));
printf(“double size is %dbyte\n”,sizeof(double));

Example: sizeof(13.56)
sizeof(239462l)
sizeof(896254ll)
sizeof(‘*’)
sizeof(a+b)
iii) address operator
General form is
&operand

Where the operand must be a variable name. This operator is used to determine the address of the memory
location allotted to a variable.

Example: int x=10,*p;


p=&x;

&x represent the address of the memory location allotted to the variable x and it is assigned to the pointer p.

p x

3472 10

3472
iv) Indirection operator
General form is

*operand

Where the operand must be a pointer.This operator is used to get the value at the address represented by the
pointer. This operator is also called de-referencing operator or value at address operator.
Example: int x=10,y,*p;
p=&x;
y=*p;
The value 10 of x is assigned to the variable y.
The expression y=*p is equivalent to the expression y=x.
v) Cast operators
These operators are used to convert the data type of operand explicitly to another type.
The general form is
(data type name)expression
Where datatype is int, double, char , pointer etc.
Example:(int)9.3 ,(double)15,(float)327,3/(int)7.2,(int)8.5/(int)4.3
Example: int a=10,b=6;
float x;
x=(float)a / (float)b;
The values of a and b are substituted in the right side expression in floating point mode and the value assigned
to x is1.6666666
Practice Programs:
1. What is the value assigned to a?
int a, x=2;
a = x + 3 * x++;
2. What is the output of the following program?
#include<stdio.h>
main()
{
int x= 5;
printf(“ %d , %d , %d”, ++x, x , x ++);
}
3. What is the output when the following program is executed?
#include<stdio.h>
main()
{
int a = 5, b = 0, c ;
c = a || b ++ ;
printf (“b = % d, c = %d”, b, c);
}
4.
What value is assigned to c when the following code is exectued?
int a=5,b=6,c;
c=(a+b>a-b)?a*b;a%b;
5. What is the output when the following code is executed?
#include<stdio.h>
main()
{
int x=10,y=15,a,b;
a=x++;
b=++y;
printf(“%d , %d ”,a,b);
}
Precedence and Associativity of all C operators:-

s.no Operators Precedence Associativity


1 () []  . 0(high) Left to right
2 ! ~ ++ -- +(unary plus) -(unary minus) * & (type) 1 Right to left
sizeof
3 / % * 2 Left to right
4 + - 3 Left to right
5 << >> 4 Left to right
6 == != 5 Left to right
7 & 6 Left to right
8 ^ 7 Left to right
9 | 8 Left to right
10 && 9 Left to right
11 || 10 Left to right
12 ?: 11 Right to left
13 = += -= *= /= %= >>= <<= &= ^= |= 12 Right to left
14 , 13(low) Left to right

Type conversions in C expressions:-

In C language we have two types of data type conversions. They are


1. Auto type conversion or implicit type conversion
2. Explicit type conversion or type casting.
Auto type conversion:-

When an operator has operators of different types, then they are converted to a common type according
to a small number of rules. In autotype conversion, it converts a “narrower” operand into a “wider” one without
losing information.
Rules:-

If either operand is long double then other operand also converted to long double data type,
Otherwise, if either operand is double then other operand also converted to double data type,
Otherwise, if either operand is float then other operand also converted to float data type,
Otherwise, if either operand is integer then other operand also converted to integer data type.

If either operand is long integer then other operand is also converted to long integer data type.

Ex:-
void main()
{
int x =3;
float z = 2,y;
y = z/x;
printf(“%f”,y);
}
In this example consider sub-expression z/x. in z/x, z is float so that other operand x will also converted to the
float data type.

Explicit type conversion or type casting:-

Explicit type conversion can be forced in any expression with a unary operator called a type casting
operator. In any expression if user wants to convert a “wider” data type to any “narrower” data type then this
type casting operator is useful. The syntax of type casting is

(type-name)expression;
Ex:- int x;
float y=5.0f;
x = (int)y;

Rules for evaluation of expression in C language:-

 First parenthesized sub-expression from left to right are evaluated.


 If parentheses are nested, then the evaluation begins with the innermost sub-expression.
When evaluating expressions the highest precedence operator will execute first, and then go for the next highest
precedence operator and so on.

Session-11 Bitwise operators


Bitwise operators:-
 C language provides 6 bitwise operators which will perform their operations on bits.
 These operators will not work on real type data members.
 Generally these are used to change the bit value or to shift the bits either to left or to right.
 The following list of symbols is used as bitwise operators.
s.no Symbol Operator meaning Unary/binary Example Precedence Associativity
1 ~ 1’s compliment Unary ~a 1(high) Right-left
2 << Left shift Binary a<<b 2 Left-right
3 >> Right shift Binary a>>b 2 Left-right
4 & Bitwise AND Binary a&b 3 Left-right
5 ^ Bitwise XOR Binary a^b 4 Left-right
6 | Bitwise OR Binary a|b 5(low) Left-right

Definitions:-

Bitwise AND(&) : if both bits are 1 then only it returns 1 otherwise it returns 0.
Bitwise OR(|) : if both bits are 0 then only it returns 0 otherwise it returns 1.
Bitwise XOR(^) : if both bits are same then it returns 0 otherwise it returns 1.
Bitwise 1’s compliment (~) : if the bit is 1 it returns 0 otherwise it returns 1.

Truth table:
Op1 Op2 Op1&Op2 Op1 | Op2 Op1^Op2 ~Op1
1 1 1 1 0 0
1 0 0 1 1 0
0 1 0 1 1 1
0 0 0 0 0 1
Ex:
void main()
{
int x=5;
int y =6;
int c;
c = x&y;
printf(“%d”,c);
c = x|y;
printf(“%d”,c);
c = x^y;
printf(“%d”,c);
c = x<<y;
printf(“%d”,c);
c = x>>y;
printf(“%d”,c);
c = ~x;
printf(“%d”,c);
printf(“%u”,c);
}

Potrebbero piacerti anche