0% found this document useful (0 votes)
10 views44 pages

C Programming Notes (Unit 1&unit 2 (Operators) )

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)
10 views44 pages

C Programming Notes (Unit 1&unit 2 (Operators) )

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/ 44

INTRODUCTION to C

(For NON-IT Programmes)

Course Code: 1BPLU105A

UNIT 1 AND UNIT 2(OPERATORS)

Prepared by:
Prof. Calabe P S Alwar
CSE, Dr AIT, Bangalore

1
ALGORITHM
Algorithm is a finite sequence of instructions, each of which has a clear meaning and can be
performed with a finite amount of effort in a finite length of time. No matter what the input values
may be, an algorithm terminates after executing a finite number of instructions.
We represent an algorithm using a pseudo language that is a combination of the constructs of a
programming language together with informal English statements.
The ordered set of instructions required to solve a problem is known as an algorithm.
The characteristics of a good algorithm are:
• Precision – the steps are precisely stated (defined).
• Uniqueness – results of each step are uniquely defined and only depend on the input
and the result of the preceding steps.
• Finiteness – the algorithm stops after a finite number of instructions are executed.
• Input – the algorithm receives input.
• Output – the algorithm produces output.
• Generality – the algorithm applies to a set of inputs.
Example
Q. Write a algorithm to find out number is odd or even?
Ans.
step 1 : start step 2 : input
number step 3 : rem=number
mod 2 step 4 : if rem=0 then
print "number even"
else
print "number odd"
endif
step 5 : stop

FLOWCHART
Flowchart is a diagrammatic representation of an algorithm. Flowchart is very helpful in writing
program and explaining program to others.
Symbols Used In Flowchart
Different symbols are used for different states in flowchart, For example: Input/Output and
decision making has different symbols. The table below describes all the symbols that are used in
making flowchart

2
Examples of flowcharts in programming
Draw a flowchart to add two numbers entered by user.

3
Draw flowchart to find the largest among three different numbers entered by user.

INTRODUCTION TO C LANGUAGE
C is a general-purpose high level language that was originally developed by Dennis Ritchie for the
Unix operating system. It was first implemented on the Digital Eqquipment Corporation PDP-11
computer in 1972.

4
The Unix operating system and virtually all Unix applications are written in the C language. C
has now become a widely used professional language for various reasons.
• Easy to learn
• Structured language
• It produces efficient programs.
• It can handle low-level activities.
• It can be compiled on a variety of computers.
Facts about C
• C was invented to write an operating system called UNIX.
• C is a successor of B language which was introduced around 1970
• The language was formalized in 1988 by the American National Standard
Institute (ANSI).
• By 1973 UNIX OS almost totally written in C.
• Today C is the most widely used System Programming Language.
• Most of the state of the art software have been implemented using C Why to use C?
C was initially used for system development work, in particular the programs that make-up the
operating system. C was adopted as a system development language because it produces code
that runs nearly as fast as code written in assembly language. Some examples of the use of C
might be:
• Operating Systems
• Language Compilers
• Assemblers
• Text Editors
• Print Spoolers
• Network Drivers
• Modern Programs
• Data Bases
• Language Interpreters
• Utilities
C Program File
All the C programs are written into text files with extension ".c" for example hello.c. You can use
"vi" editor to write your C program into a file.

5
HISTORY TO C LANGUAGE
C is a general-purpose language which has been closely associated with the UNIX operating
system for which it was developed - since the system and most of the programs that run it are
written in C.
Many of the important ideas of C stem from the language BCPL, developed by Martin Richards.
The influence of BCPL on C proceeded indirectly through the language B, which was written by
Ken Thompson in 1970 at Bell Labs, for the first UNIX system on a DEC PDP-
7. BCPL and B are "type less" languages whereas C provides a variety of data types.
In 1972 Dennis Ritchie at Bell Labs writes C and in 1978 the publication of The C Programming
Language by Kernighan & Ritchie caused a revolution in the computing world.
In 1983, the American National Standards Institute (ANSI) established a committee to provide a
modern, comprehensive definition of C. The resulting definition, the ANSI standard, or "ANSI
C", was completed late 1988.

BASIC STRUCTURE OF C PROGRAMMING

6
1. Documentation section: The documentation section consists of a set of comment lines
giving the name of the program, the author and other details, which the programmer
would like to use later.
2. Link section: The link section provides instructions to the compiler to link functions
from the system library such as using the #include directive.
3. Definition section: The definition section defines all symbolic constants such using the
#define directive.
4. Global declaration section: There are some variables that are used in more than one
function. Such variables are called global variables and are declared in the global
declaration section that is outside of all the functions. This section also declares all the
user-defined functions.
5. main () function section: Every C program must have one main function section. This
section contains two parts; declaration part and executable part
1. Declaration part: The declaration part declares all the variables used in the
executable part.
2. Executable part: There is at least one statement in the executable part. These two
parts must appear between the opening and closing braces. The program
execution begins at the opening brace and ends at the closing brace. The closing
brace of the main function is the logical end of the program. All statements in the
declaration and executable part end with a semicolon.
6. Subprogram section: If the program is a multi-function program then the subprogram
section contains all the user-defined functions that are called in the main () function.
User-defined functions are generally placed immediately after the main () function,
although they may appear in any order.

PROCESS OF COMPILING AND RUNNING C PROGRAM


We will briefly highlight key features of the C Compilation model here.

7
The C Compilation Model
The Preprocessor
The Preprocessor accepts source code as input and is responsible for
• removing comments
• Interpreting special preprocessor directives denoted by #. For example
• #include -- includes contents of a named file. Files usually called header
files. e.g o #include <math.h> -- standard library maths file.
o #include <stdio.h> -- standard library I/O file
• #define -- defines a symbolic name or constant. Macro substitution. o
#define MAX_ARRAY_SIZE 100
C Compiler
The C compiler translates source to assembly code. The source code is received from the
preprocessor.
Assembler
The assembler creates object code. On a UNIX system you may see files with a .o suffix
(.OBJ on MSDOS) to indicate object code files.
Link Editor
If a source file references library functions or functions defined in other source files the link
editor combines these functions (with main()) to create an executable file.

8
C TOKENS
C tokens are the basic buildings blocks in C language which are constructed together to write a C
program.
Each and every smallest individual unit in a C program is known as C tokens.
C tokens are of six types. They are
Keywords (eg: int, while),
Identifiers (eg: main, total),
Constants (eg: 10, 20),
Strings (eg: ―total‖, ―hello‖),
Special symbols (eg: (), {}),
Operators (eg: +, /,-,*)

C KEYWORDS
C keywords are the words that convey a special meaning to the c compiler. The keywords
cannot be used as variable names.
The list of C keywords is given below:
auto break case char const

continue default do double else

enum extern float for goto

if int long register return

short signed sizeof static struct

switch typedef union unsigned void

volatile while

C IDENTIFIERS

9
Identifiers are used as the general terminology for the names of variables, functions and arrays.
These are user defined names consisting of arbitrarily long sequence of letters and digits with
either a letter or the underscore(_) as a first character.
There are certain rules that should be followed while naming c identifiers:
They must begin with a letter or underscore (_).
They must consist of only letters, digits, or underscore. No other special character is allowed.
It should not be a keyword.
It must not contain white space.
It should be up to 31 characters long as only first 31 characters are significant.
Some examples of c identifiers:
Name Remark
_A9 Valid
Temp.var Invalid as it contains special character other than the underscore
void Invalid as it is a keyword

C CONSTANTS
A C constant refers to the data items that do not change their value during the program execution.
Several types of C constants that are allowed in C are:
Integer Constants
Integer constants are whole numbers without any fractional part. It must have at least one digit
and may contain either + or – sign. A number with no sign is assumed to be positive.
There are three types of integer constants:
Decimal Integer Constants
Integer constants consisting of a set of digits, 0 through 9, preceded by an optional – or + sign.
Example of valid decimal integer constants
341, -341, 0, 8972
Octal Integer Constants
Integer constants consisting of sequence of digits from the set 0 through 7 starting with 0 is said
to be octal integer constants.
Example of valid octal integer constants
010, 0424, 0, 0540

10
Hexadecimal Integer Constants
Hexadecimal integer constants are integer constants having sequence of digits preceded by 0x or
0X. They may also include alphabets from A to F representing numbers 10 to 15.
Example of valid hexadecimal integer constants
0xD, 0X8d, 0X, 0xbD
It should be noted that, octal and hexadecimal integer constants are rarely used in programming.
Real Constants
The numbers having fractional parts are called real or floating point constants. These may be
represented in one of the two forms called fractional form or the exponent form and may also
have either + or – sign preceding it.
Example of valid real constants in fractional form or decimal notation
0.05, -0.905, 562.05, 0.015
Representing a real constant in exponent form
The general format in which a real number may be represented in exponential or scientific form
is mantissa e exponent
The mantissa must be either an integer or a real number expressed in decimal notation. The
letter e separating the mantissa and the exponent can also be written in uppercase i.e. E
And, the exponent must be an integer.
Examples of valid real constants in exponent form are:
252E85, 0.15E-10, -3e+8
Character Constants
A character constant contains one single character enclosed within single quotes.
Examples of valid character constants
‗a‘ , ‗Z‘, ‗5‘
It should be noted that character constants have numerical values known as ASCII values, for
example, the value of ‗A‘ is 65 which is its ASCII value.
Escape Characters/ Escape Sequences
C allows us to have certain non graphic characters in character constants. Non graphic characters
are those characters that cannot be typed directly from keyboard, for example, tabs, carriage
return, etc.

11
These non graphic characters can be represented by using escape sequences represented by a
backslash() followed by one or more characters.
NOTE: An escape sequence consumes only one byte of space as it represents a single character.

STRING CONSTANTS
String constants are sequence of characters enclosed within double quotes. For example,
―hello‖
―abc‖
―hello911‖
Every sting constant is automatically terminated with a special character „‟ called thenull
character which represents the end of the string.
For example, ―hello‖ will represent ―hello‖ in the memory.
Thus, the size of the string is the total number of characters plus one for the null character.

Special Symbols
The following special symbols are used in C having some special meaning and thus, cannot be
used for some other purpose.
[] () {} , ; : * … = #

12
Braces{}: These opening and ending curly braces marks the start and end of a block of code
containing more than one executable statement.
Parentheses(): These special symbols are used to indicate function calls and function
parameters.
Brackets[]: Opening and closing brackets are used as array element reference. These indicate
single and multidimensional subscripts.

VARIABLES
A variable is nothing but a name given to a storage area that our programs can manipulate. Each
variable in C has a specific type, which determines the size and layout of the variable's memory;
the range of values that can be stored within that memory; and the set of operations that can be
applied to the variable.

The name of a variable can be composed of letters, digits, and the underscore character. It must
begin with either a letter or an underscore. Upper and lowercase letters are distinct because C is
case-sensitive. Based on the basic types explained in the previous chapter, there will be the
following basic variable types −
Type Description

char Typically a single octet(one byte). This is an integer type.

int The most natural size of integer for the machine.

float A single-precision floating point value.

double A double-precision floating point value.

void Represents the absence of type.

C programming language also allows defining various other types of variables like Enumeration,
Pointer, Array, Structure, Union, etc.

Variable Definition in C
A variable definition tells the compiler where and how much storage to create for the variable. A
variable definition specifies a data type and contains a list of one or more variables of that type as
follows −

13
type variable_list;
Here, type must be a valid C data type including char, w_char, int, float, double, bool, or any user-
defined object; and variable_list may consist of one or more identifier names separated by
commas. Some valid declarations are shown here −

int i, j, k; char
c, ch;
float f, salary;
double d;
The line int i, j, k; declares and defines the variables i, j, and k; which instruct the compiler to
create variables named i, j and k of type int.

Variables can be initialized (assigned an initial value) in their declaration. The initializer consists
of an equal sign followed by a constant expression as follows −

type variable_name = value;

Some examples are −

extern int d = 3, f = 5; // declaration of d and f.


int d = 3, f = 5; // definition and initializing d and f.
byte z = 22; // definition and initializes z. char x = 'x'; // the variable x has the
value 'x'.
For definition without an initializer: variables with static storage duration are implicitly initialized
with NULL (all bytes have the value 0); the initial value of all other variables are undefined.
Variable Declaration in C
A variable declaration provides assurance to the compiler that there exists a variable with the given
type and name so that the compiler can proceed for further compilation without requiring the
complete detail about the variable. A variable definition has its meaning at the time of compilation
only; the compiler needs actual variable definition at the time of linking the program. A variable
declaration is useful when multiple files are used.

OPERATORS AND EXPRESSIONS


C language offers many types of operators. They are,

14
1. Arithmetic operators
2. Assignment operators
3. Relational operators
4. Logical operators
5. Bit wise operators
6. Conditional operators (ternary operators)
7. Increment/decrement operators
8. Special operators

S.no Types of Operators Description

These are used to perform mathematical calculations


like addition, subtraction, multiplication, division and
modulus
1 Arithmetic_operators

These are used to assign the values for the variables in


C programs.
2 Assignment_operators

These operators are used to compare the value of two


variables.
3 Relational operators

4 Logical operators
These operators are used to perform logical

15
16
#include <stdio.h>

int main()

int a=40,b=20, add,sub,mul,div,mod;

add = a+b; sub = a-b; mul = a*b;

div = a/b;

mod = a%b;

printf("Addition of a, b is : %d\n", add);

printf("Subtraction of a, b is : %d\n", sub);

printf("Multiplication of a, b is : %d\n", mul);

printf("Division of a, b is : %d\n", div); printf("Modulus

of a, b is : %d\n", mod);

OUTPUT:
Addition of a, b is : 60
Subtraction of a, b is : 20
Multiplication of a, b is : 800
Division of a, b is : 2
Modulus of a, b is : 0

ASSIGNMENT OPERATORS IN C
In C programs, values for the variables are assigned using assignment operators.
For example, if the value ―10‖ is to be assigned for the variable ―sum‖, it can be assigned as
―sum = 10;‖

Other assignment operators in C language are given below.

Operators Example Explanation

17
Simple
assignment
operator 10 is assigned
= sum = 10 to variable sum

sum += This is same as


10 sum = sum + 10
+=

This is same as
sum = sum – 10
-= sum -= 10

sum *= This is same as


10 sum = sum * 10
*=

This is same as
sum = sum / 10
/+ sum /= 10

This is same as
sum = sum %
sum %= 10
%= 10

This is same as
sum = sum &
10
&= sum&=10

Compound sum ^= This is same as


assignment 10 sum = sum ^ 10
operators ^=

EXAMPLE PROGRAM FOR C ASSIGNMENT OPERATORS:


In this program, values from 0 – 9 are summed up and total ―45‖ is displayed as output.
Assignment operators such as ―=‖ and ―+=‖ are used in this program to assign the values and to
sum up the values.

18
# include <stdio.h>

int main() { int

Total=0,i;

for(i=0;i<10;i++)

Total+=i; // This is same as Total = Toatal+i

} printf("Total = %d",

Total);

5 == x == y x is equal to y

19
x is not equal to y
6 != x != y

EXAMPLE PROGRAM FOR RELATIONAL OPERATORS IN C


In this program, relational operator (==) is used to compare 2 values whether they are equal
are not.
If both values are equal, output is displayed as ‖ values are equal‖. Else, output is displayed as
―values are not equal‖.
Note: double equal sign (==) should be used to compare 2 values. We should not single equal
sign (=).
#include <stdio.h>

int main() {

int m=40,n=20;

if (m == n) {

printf("m and n are equal");

} else { printf("m and n are not

equal");

}
OUTPUT:

m and n are not equal

20
int main()

21
int m=40,n=20; int

o=20,p=30; if (m>n

&& m !=0)

{ printf("&& Operator : Both conditions are

true\n");

} if (o>p || p!=20) { printf("|| Operator : Only one

condition is true\n");

if (!(m>n && m !=0))

{ printf("! Operator : Both conditions are

true\n");

} else { printf("! Operator : Both conditions are

true. " \

"But, status is inverted as false\n");

}
OUTPUT:

&& Operator : Both conditions are true


|| Operator : Only one condition is true
! Operator : Both conditions are true. But, status is inverted as false

In this program, operators (&&, || and !) are used to perform logical operations on the given
expressions.

22
&& operator – ―if clause‖ becomes true only when both conditions (m>n and m! =0) is true.
Else, it becomes false.
|| Operator – ―if clause‖ becomes true when any one of the condition (o>p || p!=20) is true. It
becomes false when none of the condition is true.
! Operator – It is used to reverses the state of the operand.
If the conditions (m>n && m!=0) is true, true (1) is returned. This value is inverted by ―!‖
operator.
So, ―! (m>n and m! =0)‖ returns false (0).

BIT WISE OPERATORS IN C


These operators are used to perform bit operations. Decimal values are converted into binary values
which are the sequence of bits and bit wise operators work on these bits.
Bit wise operators in C language are & (bitwise AND), | (bitwise OR), ~ (bitwise OR), ^ (XOR),
<< (left shift) and >> (right shift).

TRUTH TABLE FOR BIT WISE OPERATION BIT WISE OPERATORS

x x
& ^
y y

x y x|y Operator_symbol Operator_name

0 0 0 0 0 & Bitwise_AND

0 1 1 0 1 | Bitwise OR

1 0 1 0 1 ~ Bitwise_NOT

1 1 1 1 0 ^ XOR

<< Left Shift

23
>> Right Shift

Consider x=40 and y=80. Binary form of these values are given below.
x = 00101000 y=
01010000
All bit wise operations for x and y are given below.
x&y = 00000000 (binary) = 0 (decimal)
x|y = 01111000 (binary) = 120 (decimal)
~x = 11111111111111111111111111 11111111111111111111111111111111010111
.. ..= -41 (decimal)
x^y = 01111000 (binary) = 120 (decimal)
x << 1 = 01010000 (binary) = 80 (decimal)
x >> 1 = 00010100 (binary) = 20 (decimal)

Note:
Bit wise NOT: Value of 40 in binary
is0000000000000000000000000000000000000000000000000010100000000000. So, all 0‘s are
converted into 1‘s in bit wise NOT operation.
Bit wise left shift and right shift : In left shift operation ―x << 1 ―, 1 means that the bits will
be left shifted by one place. If we use it as ―x << 2 ―, then, it means that the bits will be left
shifted by 2 places.

EXAMPLE PROGRAM FOR BIT WISE OPERATORS IN C


In this example program, bit wise operations are performed as shown above and output is displayed
in decimal format.
#include <stdio.h> int

main()

int m = 40,n = 80,AND_opr,OR_opr,XOR_opr,NOT_opr ;

AND_opr = (m&n);

OR_opr = (m|n);

24
NOT_opr = (~m); XOR_opr = (m^n);

printf("AND_opr value = %d\n",AND_opr );

printf("OR_opr value = %d\n",OR_opr );

printf("NOT_opr value = %d\n",NOT_opr );

printf("XOR_opr value = %d\n",XOR_opr );

printf("left_shift value = %d\n", m << 1); printf("right_shift

value = %d\n", m >> 1);

OUTPUT:
AND_opr value = 0
OR_opr value = 120
NOT_opr value = -41
XOR_opr value = 120
left_shift value = 80
right_shift value = 20

CONDITIONAL OR TERNARY OPERATORS IN C


Conditional operators return one value if condition is true and returns another value is condition
is false.
This operator is also called as ternary operator.
Syntax : (Condition? true_value: false_value);

Example : (A > 100 ? 0 : 1);

In above example, if A is greater than 100, 0 is returned else 1 is returned. This is equal to if else
conditional statements.

EXAMPLE PROGRAM FOR CONDITIONAL/TERNARY OPERATORS IN C


#include <stdio.h>

int main() {

int x=1, y ;

25
y = ( x ==1 ? 2 : 0 ) ; printf("x

value is %d\n", x); printf("y

value is %d", y);

OUTPUT:
x value is 1
y value is 2

C – Increment/decrement Operators
PREVNEXT
Increment operators are used to increase the value of the variable by one and decrement operators
are used to decrease the value of the variable by one in C programs.
Syntax:
Increment operator: ++var_name ;( or) var_name++; Decrement
operator: – -var_name; (or) var_name – -;

Example:
Increment operator : ++ i ; i ++ ;
Decrement operator : – – i ; i – – ;

EXAMPLE PROGRAM FOR INCREMENT OPERATORS IN C


In this program, value of ―i‖ is incremented one by one from 1 up to 9 using ―i++‖ operator and
output is displayed as ―1 2 3 4 5 6 7 8 9‖.
//Example for increment operators

#include <stdio.h>

int main() {

int i=1;

while(i<10)
{

printf("%d ",i);

i++;

26
}

}
OUTPUT:
123456789

EXAMPLE PROGRAM FOR DECREMENT OPERATORS IN C


In this program, value of ―I‖ is decremented one by one from 20 up to 11 using ―– ‖i operator and
output is displayed as ―20 19 18 17 16 15 14 13 12 11‖.

//Example for decrement operators

#include <stdio.h>

int main() { int

i=20;

while(i>10)
{

printf("%d ",i);

i--;

27
}

OUTPUT:
20 19 18 17 16 15 14 13 12 11

DIFFERENCE BETWEEN PRE/POST INCREMENT & DECREMENT OPERATORS


IN C
Below table will explain the difference between pre/post increment and decrement operators in
C.
S.no Operator type Operator Description

1 Pre increment
++i Value of i is

28
#include <stdio.h>

int main() {

int i=0;

while(++i < 5 )
{

printf("%d ",i);

return 0;

}
OUTPUT:
1234

Step 1 : In above program, value of ―i‖ is incremented from 0 to 1 using pre -increment
operator.
Step 2 : This incremented value ―1‖ is compared with 5 in while expression.
Step 3 : Then, this incremented value ―1‖ is assigned to the variable ―i‖.
Above 3 steps are continued until while expression becomes false and output is displayed as
―1 2 3 4‖.

EXAMPLE PROGRAM FOR POST – INCREMENT OPERATORS IN C


#include <stdio.h>

int main() {

int i=0;

while(i++ < 5 )

printf("%d ",i);

return 0;

}
OUTPUT:

29
12345

Step 1 : In this program, value of i ―0‖ is compared with 5 in while expression.


Step 2 : Then, value of ―i‖ is incremented from 0 to 1 using post-increment operator.
Step 3 : Then, this incremented value ―1‖ is assigned to the variable ―i‖.
Above 3 steps are continued until while expression becomes false and output is displayed as
―1 2 3 4 5‖.

EXAMPLE PROGRAM FOR PRE – DECREMENT OPERATORS IN C


#include <stdio.h>

int main() {

int i=10;

while(--i > 5 )

printf("%d ",i);

return 0;
}

OUTPUT:
9876

Step 1 : In above program, value of ―i‖ is decremented from 10 to 9 using pre -decrement
operator.
Step 2 : This decremented value ―9‖ is compared with 5 in while expression.
Step 3 : Then, this decremented value ―9‖is assigned to the variable ―i‖.
Above 3 steps are continued until while expression becomes false and output is displayed as
―9 8 7 6‖.

EXAMPLE PROGRAM FOR POST – DECREMENT OPERATORS IN C:


#include <stdio.h>

int main()

30
int i=10;

while(i-- > 5 )

{
printf("%d ",i);

return 0;

31
EXAMPLE PROGRAM FOR & AND * OPERATORS IN C
In this program, ―&‖ symbol is used to get the address of the variable and ―*‖ symbol is
used to get the value of the variable that the pointer is pointing to. Please refer C – pointer
topic to know more about pointers.

32
#include <stdio.h>

int main() { int

*ptr, q; q = 50;

/* address of q is assigned to ptr */

ptr = &q;

/* display q's value using ptr variable */

printf("%d", *ptr); return 0;

OUTPUT:

50

EXAMPLE PROGRAM FOR SIZEOF() OPERATOR IN C


sizeof() operator is used to find the memory space allocated for each C data types.
#include <stdio.h>

#include <limits.h> int

main()

{ int

a;

char b;
float c;

double d; printf("Storage size for int data type:%d

\n",sizeof(a)); printf("Storage size for char data type:%d

\n",sizeof(b)); printf("Storage size for float data type:%d

\n",sizeof(c)); printf("Storage size for double data

type:%d\n",sizeof(d)); return 0;

33
OUTPUT:

Storage size for int data type:4


Storage size for char data type:1
Storage size for float data type:4
Storage size for double data type:8

EXPRESSIONS
Arithmetic expression in C is a combination of variables, constants and operators written in a
proper syntax. C can easily handle any complex mathematical expressions but these
mathematical expressions have to be written in a proper syntax. Some examples of mathematical
expressions written in proper syntax of C are
Note: C does not have any operator for exponentiation.

C OPERATOR PRECEDENCE AND ASSOCIATIVITY

C operators in order of precedence (highest to lowest). Their associativity indicates in what order
operators of equal precedence in an expression are applied.
Operator Description Associativity
() Parentheses (function call) (see Note 1) left-to-right
[] Brackets (array subscript)
. Member selection via object name
-> Member selection via pointer
++ -- Postfix increment/decrement (see Note 2)
++ -- Prefix increment/decrement right-to-left
+- Unary plus/minus
!~ Logical negation/bitwise complement
(type) Cast (convert value to temporary value of type)
* Dereference
& Address (of operand)
sizeof Determine size in bytes on this implementation
* / % Multiplication/division/modulus left-to-right
+ - Addition/subtraction left-to-right
<< >> Bitwise shift left, Bitwise shift right left-to-right
< <= Relational less than/less than or equal to left-to-right
> >= Relational greater than/greater than or equal to
== != Relational is equal to/is not equal to left-to-right

34
& Bitwise AND left-to-right
^ Bitwise exclusive OR left-to-right
| Bitwise inclusive OR left-to-right
&& Logical AND left-to-right
|| Logical OR left-to-right
?: Ternary conditional right-to-left
= Assignment right-to-left
+= -= Addition/subtraction assignment
*= /= Multiplication/division assignment
%= &= Modulus/bitwise AND assignment
^= |= Bitwise exclusive/inclusive OR assignment
<<= >>= Bitwise shift left/right assignment
, Comma (separate expressions) left-to-right
Note 1:
Parentheses are also used to group sub-expressions to force a
different precedence; such parenthetical expressions can be
nested and are evaluated from inner to outer.
Note 2:
Postfix increment/decrement have high precedence, but the actual
increment or decrement of the operand is delayed (to be
accomplished sometime before the statement completes
execution). So in the statement y = x * z++; the current value of z
is used to evaluate the expression (i.e., z++ evaluates to z) and z
only incremented after all else is done.

EVALUATION OF EXPRESSION
At first, the expressions within parenthesis are evaluated. If no parenthesis is present, then the
arithmetic expression is evaluated from left to right. There are two priority levels of operators in
C.
High priority: * / %
Low priority: + -
The evaluation procedure of an arithmetic expression includes two left to right passes through the
entire expression. In the first pass, the high priority operators are applied as they are encountered
and in the second pass, low priority operations are applied as they are encountered.

35
Suppose, we have an arithmetic expression as:
x = 9 – 12 / 3 + 3 *2 - 1
This expression is evaluated in two left to right passes as:
First Pass
Step 1: x = 9-4 + 3 * 2 – 1
Step 2: x = 9 – 4 + 6 – 1
Second Pass
Step 1: x = 5 + 6 – 1
Step 2: x = 11 – 1
Step 3: x = 10
But when parenthesis is used in the same expression, the order of evaluation gets changed.
For example,
x = 9 – 12 / (3 + 3) * (2 – 1)
When parentheses are present then the expression inside the parenthesis are evaluated first from
left to right. The expression is now evaluated in three passes as:
First Pass
Step 1: x = 9 – 12 / 6 * (2 – 1)
Step 2: x= 9 – 12 / 6 * 1
Second Pass
Step 1: x= 9 – 2 * 1
Step 2: x = 9 – 2
Third Pass
Step 3: x= 7
There may even arise a case where nested parentheses are present (i.e. parenthesis inside
parenthesis). In such case, the expression inside the innermost set of parentheses is evaluated first
and then the outer parentheses are evaluated.
For example, we have an expression as:
x = 9 – ((12 / 3) + 3 * 2) – 1
The expression is now evaluated as:
First Pass:

36
Step 1: x = 9 – (4 + 3 * 2) – 1
Step 2: x= 9 – (4 + 6) – 1
Step 3: x= 9 – 10 -1
Second Pass
Step 1: x= - 1 – 1
Step 2: x = -2
Note: The number of evaluation steps is equal to the number of operators in the arithmetic
expression.

TYPE CONVERSION IN EXPRESSIONS


When variables and constants of different types are combined in an expression then they are
converted to same data type. The process of converting one predefined type into another is called
type conversion.
Type conversion in c can be classified into the following two types:
Implicit Type Conversion
When the type conversion is performed automatically by the compiler without programmer‘s
intervention, such type of conversion is known as implicit type conversion or type promotion.
The compiler converts all operands into the data type of the largest operand.
The sequence of rules that are applied while evaluating expressions are given below:
All short and char are automatically converted to int, then,
If either of the operand is of type long double, then others will be converted to long double and
result will be long double.
Else, if either of the operand is double, then others are converted to double.
Else, if either of the operand is float, then others are converted to float.
Else, if either of the operand is unsigned long int, then others will be converted to unsigned long
int.
Else, if one of the operand is long int, and the other is unsigned int, then if a long int can
represent all values of an unsigned int, the unsigned int is converted to long int. otherwise, both
operands are converted to unsigned long int.
Else, if either operand is long int then other will be converted to long int.
Else, if either operand is unsigned int then others will be converted to unsigned int.

37
It should be noted that the final result of expression is converted to type of variable on left side of
assignment operator before assigning value to it.
Also, conversion of float to int causes truncation of fractional part, conversion of double to float
causes rounding of digits and the conversion of long int to int causes dropping of excess higher
order bits.

Explicit Type Conversion


The type conversion performed by the programmer by posing the data type of the expression of
specific type is known as explicit type conversion.
The explicit type conversion is also known as type casting.
Type casting in c is done in the following form:
(data_type)expression; where, data_type is any valid c data type, and expression
may be constant, variable or expression.
For example, x=(int)a+b*d;
The following rules have to be followed while converting the expression from one type to
another to avoid the loss of information:
All integer types to be converted to float.
All float types to be converted to double.
All character types to be converted to integer.

FORMATTED INPUT AND OUTPUT


The C Programming Language is also called the Mother of languages. The C language was
developed by Dennis Ritchie between 1969 and 1973 and is a second and third generation of
languages. The C language provides both low and high level features it provides both the power
of low-level languages and the flexibility and simplicity of high-level languages.
C provides standard functions scanf() and printf(), for performing formatted input and output.
These functions accept, as parameters, a format specification string and a list of variables. The
format specification string is a character string that specifies the data type of each variable to be
input or output and the size or width of the input and output.
Now to discuss formatted output in functions.

38
Formatted Output
The function printf() is used for formatted output to standard output based on a format
specification. The format specification string, along with the data to be output, are the parameters
to the printf() function.
Syntax:
printf (format, data1, data2,… ......);

In this syntax format is the format specification string. This string contains, for each variable to
be output, a specification beginning with the symbol % followed by a character called the
conversion character.
Example:
printf (―%c‖, data1);
The character specified after % is called a conversion character because it allows one data type to
be converted to another type and printed.
See the following table conversion character and their meanings.
Conversion Meaning
Character
d The data is converted to decimal (integer)
c The data is taken as a character.
s The data is a string and character from the string , are printed until a NULL,
character is reached.

f The data is output as float or double with a default Precision 6.


Symbols Meaning
\n For new line (linefeed return)
\t For tab space (equivalent of 8 spaces)
Example
printf (―%c\n‖,data1);
The format specification string may also have text. Example
printf (―Character is:‖%c\n‖, data1);
The text "Character is:" is printed out along with the value of data1.
Example with program

39
#include<stdio.h>
#include<conio.h>
Main()
{
Char alphabh="A"; int
number1= 55; float
number2=22.34;
printf(―char=
%c\n‖,alphabh); printf(―int=
%d\n‖,number1);
printf(―float=
%f\n‖,number2); getch();
clrscr(); retrun 0;
}
Output Here…
char =A int=
55
flaot=22.340000
What is the
output of the
statement?

printf(―Integer is: %d; Alphabet is:%c\n‖,number1, alpha);


Where number1 contains 44 and alpha contains "Krishna Singh".
Give the answer below.
Between the character % and the conversion character, there may be:
• A minus sign: Denoting left adjustment of the data.
• A digit: Specifying the minimum width in which the data is to be output, if the data has a
larger number of characters then the specified width occupied by the output is larger. If
the data consists of fewer characters then the specified width, it is padded to the right or
to the left (if minus sign is not specified) with blanks. If the digit is prefixed with a zero,
the padding is done with zeros instead of blanks.

40
• A period: Separating the width from the next digit.
• A digit following the period: specifying the precision (number of decimal places for
numeric data) or the maximum number of characters to be output.
• Letter 1: To indicate that the data item is a long integer and not an int.

Format specification string Data Output


|%2d| 9 |9|
|%2d| 123 |123|
|%03d| 9 |009|
|%-2d| 7 |7|
|%5.3d| 2 |002|
|%3.1d| 15 |15|
|%3.5d| 15 |0015|
|%5s| ―Output sting‖ |Output string|
|%15s| ―Output sting‖ |Output string|
|%-15s| ―Output sting‖ |Output string|
|%15.5s| ―Output sting‖ |Output string|
|%.5s| ―Output sting‖ |Output|
|%15.5s| ―Output sting‖ |Output|
|%f| 87.65 |87.650000|
|%.4.1s| 87.65 |87.71|

Example based on the conversion character:


#include<stdio.h>
#include<conio.h>
main()
{

41
Int num=65; printf(―Value of num is : %d\n:, num);
printf(―Character equivalent of %d is %c\n‖, num ,
num); getch(); clrscr(); rerurn o; }
Output Here…
char =A int= 55
flaot=22.340000
Formatted Input
The function scanf() is used for formatted input from standard input and provides many of the
conversion facilities of the function printf(). Syntax
scanf (format, num1, num2,……);
The function scnaf() reads and converts characters from the standards input depending on the
format specification string and stores the input in memory locations represented by the other
arguments (num1, num2,….). For Example:
scanf(― %c %d‖,&Name, &Roll No);
Note: the data names are listed as &Name and &Roll No instead of Name and Roll No
respectively. This is how data names are specified in a scnaf() function. In case of string type
data names, the data name is not preceded by the character &.
Example with program
Write a function to accept and display the element number and the weight of a proton. The
element number is an integer and weight is fractional.
Solve here:
#include<stdio.h>
#include<conio.h>
main()
{
Int e_num; Float e_wt; printf (―Enter the Element No.
and Weight of a Proton\n‖); scanf (―%d %f‖,&e_num,
&e_wt); printf (―The Element No.is:‖,e_num); printf
(―The Weight of a Proton is: %f\n‖, e_wt); getch();
return 0;
}

42
UNIT-II
CONTROL STRUCTURES, ARRAYS AND STRINGS

DECISION STATEMENTS
If statement: Syntax
:
if(expression)
statement1;
Explanation :
• Expression is Boolean Expression It may have true or false value

43
Meaning of If Statement :
• It Checks whether the given Expression is Boolean or not !!
• If Expression is True Then it executes the statement otherwise jumps to next_instruction
Sample Program Code :
void main()
{ int
a=5,b=6,c;
c=a+b;

if (c==11)
printf("Execute me 1");

printf("Execute me 2"); }
Output :
Execute me 1

If Statement :
if(conditional)
{
Statement No 1
Statement No 2
Statement No 3
.

44

You might also like