0% found this document useful (0 votes)
33 views28 pages

Unit 2 New (C Prog)

Uploaded by

hawkff629
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)
33 views28 pages

Unit 2 New (C Prog)

Uploaded by

hawkff629
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/ 28

UNIT-2 (contents)

PROGRAM: A computer program is a set of instructions for a computer to perform a specific task. programs
are written in a programming language , then translated into machine code by a compiler and linker so that the
computer can execute it directly or run it line by line (interpreted) by an interpreter program.
PROGRAMMING: The act or process of planning or writing a computer program.
Every program is limited by the language which is used to write it. C is a programmer's language. Unlike
BASIC or Pascal, C was not written as a teaching aid, but as an implementation language. C is a computer
language and a programming tool which has grown popular because programmers like it! It is a tricky language
but a masterful one. C is ideally suited to modern computers and modern programming.
C Language:

The C is a general-purpose, procedural, imperative computer programming language developed in


1972 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system. C
is the most widely used computer language.
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 Institue (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

USES OF C
• C language is primarily used for system programming. The portability, efficiency, the ability to access
specific hardware addresses and low runtime demand on system resources makes it a good choice for
implementing operating systems and embedded system applications.
• C has been so widely accepted by professionals that compilers, libraries, and interpreters of other
programming languages are often implemented in C.
• For portability and convenience reasons, C is sometimes used as an intermediate language by
implementations of other languages.
• C is widely used to implement end-user applications.

FILES USED IN A C PROGRAM

Files in a C program

Source File Header File Object File Executable File

Source code file


• The source code file contains the source code of the program. The file extension of any C source code
file is “.c”. This file contains C source code that defines the main function and maybe other functions.
The main() is the starting point of execution when you successfully compile and run the program. A C
program in general may include even other source code files (with the file extension .c).
Header Files
• When working with large projects, it is often desirable to make sub-routines and store them in a
different file known as header file. The advantage of header files can be realized when
a) The programmer wants to use the same subroutines in different programs.
b) The programmer wants to change, or add, subroutines, and have those changes be reflected in all
other programs.
• Conventionally, header files names ends with a “.h” extension and its name can use only letters, digits,
dashes, and underscores.
• While some standard header files are available in C, but the programmer may also create his own user
defined header files
Object Files
• Object files are generated by the compiler as a result of processing the source code file. Object files
contain compact binary code of the function definitions. Linker uses this object file to produce an
executable file (.exe file) by combining the of object files together. Object files have a “.o” extension,
although some operating systems including Windows and MS-DOS have a “.obj” extension for the
object file.
Binary Executable File
• The binary executable file is generated by the linker. The linker links the various object files to produce
a binary file that can be directly executed. On Windows operating system, the executable files have
“.exe” extension.

COMPILING AND EXECUTING C PROGRAMS


The compilation process in the figure is done in two steps. In the first step, the preprocessor program
reads the source file as text, and produces another text file as output. Source code lines which begin with the
hash symbol are actually not written in C but in the preprocessor language. The output of the preprocessor is a
text file which does not contain any preprocessor statements. This file is ready to be processed by the compiler.
The linker combines the object file with library routines (supplied with the compiler) to produce the final
executable file.
Pre-
File proce
Object
ss Files

Files Files Files

Pre-
File proce Files

Files

STRUCTURE OF PROGRAM

The structure of a C program is a protocol (rules) to the programmer, while writing a C program. The general
basic structure of C program is shown in the figure below. The whole program is controlled within main ( )
along with left brace denoted by “{” and right braces denoted by “}”. If you need to declare local variables and
executable program structures are enclosed within “{” and “}” is called the body of the main function. The
main ( ) function can be preceded by documentation, preprocessor statements and global declarations.
Documentations:

The documentation section consist of a set of comment lines giving the name of the program, the another name
and other details, which the programmer would like to use later.
Preprocessor Statements (DIRECTIVE)
These statements instruct the compiler to include C preprocessors such as header files and symbolic constants
before compiling the C program. Some of the preprocessor statements are listed below.
The preprocessor statement begin with # symbol

Global Declarations
The variables are declared before the main ( ) function as well as user defined functions are called global
variables. These global variables can be accessed by all the user defined functions including main ( ) function.
The main ( ) function
Each and Every C program should contain only one main ( ). The C program execution starts with main ( )
function. No C program is executed without the main function. The main ( ) function should be written in small
(lowercase) letters and it should not be terminated by semicolon. Main ( ) executes user defined program
statements, library functions and user defined functions and all these statements should be enclosed within left
and right braces.
Braces
Every C program should have a pair of curly braces ({, }). The left braces indicates the beginning of the main (
) function and the right braces indicates the end of the main ( ) function. These braces can also be used to
indicate the user-defined functions beginning and ending. These two braces can also be used in compound
statements.
Local Declarations
The variable declaration is a part of C program and all the variables are used in main ( ) function should be
declared in the local declaration section is called local variables. Not only variables, we can also declare arrays,
functions, pointers etc. These variables can also be initialized with basic data types. For examples.
Code:
main ( )
{
int sum = 0;
int x;
float y;
}
Here, the variable sum is declared as integer variable and it is initialized to zero. Other variables declared as int
and float and these variables inside any function are called local variables.
Program statements
These statements are building blocks of a program. They represent instructions to the computer to perform a
specific task (operations). An instruction may contain an input-output statements, arithmetic statements, control
statements, simple assignment statements and any other statements and it also includes comments that are
enclosed within /* and */ . The comment statements are not compiled and executed and each executable
statement should be terminated with semicolon.
User defined functions
These are subprograms, generally, a subprogram is a function and these functions are written by the user are
called user ; defined functions. These functions are performed by user specific tasks and this also contains set of
program statements. They may be written before or after a main () function and called within main () function.
This is an optional to the programmer.
Now, let us write a small program to display some message shown below.
Code:
# include <stdio.h>
main()
{
printf ("welcome to the world of C/n");
}

CHARACTER SET: Character set are the set of alphabets, letters and some special characters that are valid in
C language.
Alphabets: Uppercase: A B C .................................... X Y Z
Lowercase: a b c ...................................... x y z
Digits: 0 1 2 3 4 5 6 8 9
Special Characters:
Special Characters in C language
, < > . _ ( ) ; $ : % [ ] # ?
' & { } " ^ ! * / | - \ ~ +
White space Characters: blank space, new line, horizontal tab, carriage return and form feed.

USING COMMENTS

• It is a good programming practice to place some comments in the code to help the reader understand the
code clearly.
• Comments are just a way of explaining what a program does. It is merely an internal program
documentation.
• The compiler ignores the comments when forming the object file. This means that the comments are
non-executable statements.
C supports two types of commenting.
• // is used to comment a single statement. This is known as a line comment. A line comment can be
placed anywhere on the line and it does not require to be specifically ended as the end of the line
automatically ends the line.
• /* is used to comment multiple statements. A /* is ended with */ and all statements that lie within these
characters are commented.
C TOKENS
Tokens are individual words and punctuation marks in passage of text. In C, program the smallest individual
units are known as C Tokens. C has six types of Tokens. The Tokens are shown in figure.
1.Keywords

• C has a set of 32 reserved words often known as keywords. All keywords are basically a sequence of
characters that have a fixed meaning. By convention all keywords must be written in lowercase (small)
letters.
• Example: for, while, do-while, auto break, case, char, continue, do, double, else, enum, extern, float,
goto, if, int, long, register, return, short, signed, sizeof, static, struct, switch, typedef, union, unsigned,
void, volatile.

2.Identifiers
• Identifiers are names given to program elements such as variables, arrays and functions.
Rules for forming identifier name
▪ it cannot include any special characters or punctuation marks (like #, $, ^, ?, ., etc) except the
underscore"_".
▪ There cannot be two successive underscores
▪ Keywords cannot be used as identifiers
▪ The names are case sensitive. So, example, “FIRST” is different from “first” and “First”.
▪ It must begin with an alphabet or an underscore.
▪ It can be of any reasonable length. Though it should not contain more than 31 characters.

3.Constant

Constants in C refer to fixed values that do not change during the executing of a program. C Support several
types of constants are listed below.

1. Numeric Constants
i. Integer Constants: An "integer constant" is a decimal (base 10), octal (base 8), or
hexadecimal (base 16) number that represents an integral value. Use integer constants
to represent integer values that cannot be changed. If an integer constant begins with 0x
or 0X, it is hexadecimal. If it begins with the digit 0, it is octal. Otherwise, it is assumed
to be decimal.
ii. Real Constants: A "floating-point constant" is a decimal number that represents a signed real
number. The representation of a signed real number includes an integer portion, a fractional
portion, and an exponent. Use floating-point constants to represent floating-point values that
cannot be changed.
You can omit either the digits before the decimal point (the integer portion of the value) or the
digits after the decimal point (the fractional portion), but not both. You can leave out the
decimal point only if you include an exponent. No white-space characters can separate the
digits or characters of the constant.
Floating-point constants have type float, double, or long double. A floating-point constant
without an f, F, l, or L suffix has type double. If the letter f or F is the suffix, the constant has
type float. If suffixed by the letter l or L, it has type long double
2. Character Constants
i. Single Character Constants:"character constant" is formed by enclosing a single character
from the represent able character set within single quotation marks (' '). Character constants are
used to represent characters in the execution character set.
Escape-sequence: Character combinations consisting of a backslash (\) followed by a
letter or by a combination of digits are called "escape sequences."
Escape Sequence Represents
\a Bell (alert)
\b Backspace
\f Formfeed
\n New line
\r Carriage return
\t Horizontal tab
\v Vertical tab
\' Single quotation mark
\" Double quotation mark
\\ Backslash
\? Literal question mark
\ ooo ASCII character in octal notation
\x hh ASCII character in hexadecimal notation
Unicode character in hexadecimal notation if this escape sequence is
used in a wide-character constant or a Unicode string literal.
\x hhhh
For example, WCHAR f = L'\x4e00' or WCHAR b[] = L"The Chinese
character for one is \x4e00".

 Although it consists of two characters, it represents single character.


 Each escape sequence has unique ASCII value.
 Each and Every combination starts with back slash(\)
 They are non-printable characters.
 It can also be expressed in terms of octal digits or hexadecimal sequence.
 Escape sequence in character constants and string literals are replaced by their equivalent and
then adjacent string literals are concatenated
 Escape Sequences are preprocessed by Preprocessor.
1. Tab : ‘\t’ Character
{
printf("Hello\t");
}

Cursor Position After Execution of printf :


Hello _

2. New Line Character : ‘\n’ Character

1. It is New Line Character

Takes Control to new Line


#include<stdio.h>

int main()
{
printf("Hello\n");
return(0);
}

Cursor Position After printf :


Hello
_

3. Backslash : ‘\b’ Character

 It is Backslash Character
 Takes Control one position back

#include<stdio.h>

int main()
{
printf("Hello\b");
return(0);
}

Cursor Position :
Hell_

4. Carriage Return: ‘\r’ Character

 It is Carriage Return Character


 Takes Control to First Position in the Line

printf("Hello\r");

Cursor Position :
Note : Cursor on ‘H’ character from Word Hello
_allo
4. Audible Return : ‘\a’ Character

 It is audible Return Character


 Beeps Sound

printf("Hello\a");

What will happen ?

Hello

ii. String constant: Collection of characters enclosed in double quotes.

4. String : Collection of characters terminated with special character known as NULL character.
String in C language is enclosed in double quotes.
Example --- “hello” “welcome”.
5. Operator: Operator is a symbol which operates on certain data type.There are many types of operator
present in c language.
Example +, %, > < etc.
6. Special symbol:
( ) ; $ :
DATA TYPES

Primitive or fundamental data type


void – used to denote the type with no values
int – used to denote an integer type
char – used to denote a character type
float, double – used to denote a floating point type
Derived Data Types
Array – a finite sequence (or table) of variables of the same data type
Pointer - int *, float *, char * – used to denote a pointer type, which is a memory address type.
Function-- Set of statements grouped together into single logical unit is refered to as function.
various data types used in c
Enumerated type (also called enumeration or enum) is a data type consisting of a set of named values called elements,
members or enumerators of the type. The enumerator names are usually identifiers that behave as constants in the
language. A variable that has been declared as having an enumerated type can be assigned any of the enumerators as a
value. In other words, an enumerated type has values which are different from each other, and which can be compared and
assigned, but which do not have any particular concrete representation in the computer's memory; compilers and
interpreters can represent them arbitrarily.
ENUMERATED DATA TYPES Enumerated data type variables can only assume values which have been previously
declared.
enum month { jan = 1, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec };
enum month this_month;
this_month = feb;
eg. What will be output of following program?
void main()
{
enum colour { green,red=5,blue,white,yellow=10,pink };
printf(“%d %d %d %d %d %d,green,red,blue,white,yellow,pink}
};
Output: 0 5 6 7 8 10 11
VARIABLES IN C

• A variable is defined as a meaningful name given to the data storage location in computer memory.
• When using a variable, we actually refer to address of the memory where the data is stored. C language
supports two basic kinds of variables.
• Numeric variables can be used to store either integer values or floating point values.
• While an integer value is a whole numbers without a fraction part or decimal point, a floating point
number, can have a decimal point in them.
• Numeric values may also be associated with modifiers like short, long, signed and unsigned.
• By default, C automatically a numeric variable signed..
• Character variables can include any letter from the alphabet or from the ASCII chart and numbers 0 – 9
that are put between single quotes.

To declare a variable specify data type of the variable followed by its name.
Variable names should always be meaningful and must reflect the purpose of their usage in the program.
Variable declaration always ends with a semicolon. Example,
int emp_num;
float salary;
char grade;
double balance_amount;
unsigned short int acc_no;

Declaration and Definition:


S. No. Declaration Definition
1. Declaring a variable & function means Defining a variable & function means declaring
describing its type to the compiler and also it and also allocating space to hold the
allocating space to hold the variable’s data. variable’s data. You can also initialize a
variable at the time it is defined.
2. In case of a variable, a variable can be But in this, definition of a variable is defined
declared once. only one time in a program.
3. For example int a; For example int a=7;
DATA TYPE QUALIFIERS
Each of these data type has got qualifiers. The purpose of a qualifier is to manipulate the range of a particular
data type or its size.
Size qualifier
Size qualifiers alter the size of basic data type. The keywords long and short are two size qualifiers.
Example: Integer data type int is normally 2 byte. If you declare it as long int – then its size will increase from
2 bytes to 4 bytes. Similarly if you declare it as short int – its size will reduce from 2 bytes to 1 byte.
Sign qualifier
Whether a variable can hold only positive value or both values is specified by sign qualifiers. Keywords signed
and unsigned are used for sign qualifiers.
Example: int – when declared normally is of 2 bytes. If it is declared as unsigned int – then its range is from 0
to 65535. In other case, if it is declared as signed int – then its range is from (-32767 to 32768). In the case of
signed int, one bit (MSB) is used to store the sign of the integer +/-. This basically means the programmer will
not be able to display/store a number higher than 65535 using unsigned int. Similarly it is not possible to
manipulate a number beyond -32767 or +327678 using signed int.
Constant qualifiers
Constant qualifiers can be declared with keyword const. An object declared by const cannot be modified.

const int p=20;


The value of p cannot be changed in the program.
Volatile qualifiers:
A variable should be declared volatile whenever its value can be changed by some external sources outside
program. Keyword volatile is used to indicate volatile variable.

STREAMS
• A stream acts in two ways. It is the source of data as well as the destination of data.
• C programs input data and output data from a stream. Streams are associated with a physical device
such as the monitor or with a file stored on the secondary memory.
• In a text stream, sequence of characters is divided into lines with each line being terminated with a new-
line character (\n). On the other hand, a binary stream contains data values using their memory
representation.
• we can do input/output from the keyboard/monitor or from any file but in this chapter we will assume
that the source of data is the keyboard and destination of the data is the monitor.

Streams in a C
program

Text Binary
Stream Stream

INPUT OUTPUT IN C
C Standard Library Functions
C Standard library functions or simply C Library functions are inbuilt functions in C programming. Function
prototype and data definitions of these functions are written in their respective header file. For example: If you
want to use printf() function, the header file <stdio.h> should be included.
#include <stdio.h>
int main()
{

/* If you write printf() statement without including header file, this program will show error. */
printf("Catch me if you can.");
}
There is at least one function in any C program, i.e., the main() function (which is also a library function).
This program is called at program starts.
There are many library functions available in C programming to help the programmer to write a good efficient
program.
1).Formated Input Output Functions:-

These function are used to Input data from a standard Input unit such as Keyboard and to get the result
on standard output unit such as Monitor . As name suggest , these function follow a basic fix format .
There are two Input Output functions .
1. printf() 2. scanf()

THE PRINTF() FUNCTION


• The printf function is used to display information required to the user and also prints the values of the
variables. Its syntax can be given as
printf (“conversion string”, variable list);
• The parameter control string is a C string that contains the text that has to be written on to the standard
output device. The prototype of the control string can be given as below
%[flags][width][.precision][length]specifier
specifier Qualifying Input
flag description
c For single character
- Left-justify within the data given d For decimal values
field width
+ Displays the data with its numeric F For floating point numbers
sign (either + or -) E, e Floating point numbers in exponential format
# Used to provide additional
specifiers like o, x, X, 0, 0x or 0X G, G Floating point numbers in the shorter of e format
for octal and hexa decimal values
o For Octal number.
respectively for values different
than zero. s For a sequence of (string of) characters
0 The number is left-padded with
zeroes (0) instead of spaces u For Unsigned decimal value
x,X For Hexadecimal value.

length Description
h When the argument is a short int or unsigned short int.
l When the argument is a long int or unsigned long int for integer specifiers.

L When the argument is a long double (used for floating point specifiers)

THE SCANF() FUNCTION


• The scanf() is used to read formatted data from the keyboard. The syntax can be given as,
scanf (“control string”, arg1, arg2, ………….argn);
• The control string specifies the type and format of the data that has to be obtained from the keyboard
and stored in the memory locations pointed by the arguments arg1, arg2,…, argn. The prototype of the
control string can be give as:
[=%[*][width][modifiers]type=]
• * is an optional argument that suppresses assignment of the input field. That is, it indicates that data
should be read from the stream but ignored (not stored in the memory location).
• width is an optional argument that specifies the maximum number of characters to be read.
• modifiers is an optional argument that can be h, l or L for the data pointed by the corresponding
additional arguments. Modifier h is used for short int or unsigned short int, l is used for long int,
unsigned long int or double values. Finally, L is used long double data values.
• Type is same as specifier in printf()

EXAMPLE OF printf() and scanf():


void main()
{
int num;
float fnum;
char ch, str[10];
double dnum;
short snum;
long int lnum;
printf(“\n Enter the values : “);
scanf("%d %f %c %s %e %hd %ld", &num, &fnum, &ch, str, &dnum, &snum, &lnum);
printf("\n num = %d \n fnum = %.2f \n ch = %c \n str = %s \n dnum = %e \n snum = %hd \n lnum =
%ld", num, fnum, ch, str, dnum, snum, lnum);
}

Example:
#include <stdio.h>
int main()
{
printf("%d\n",1234);
printf("%10d\n",1234);
printf("%2d\n",1234);
printf("%-10d\n",1234);
printf("%010d\n",1234);
printf("%+10d\n",1234);
return 0;
}
Output:
1234
1234
1234
1234
0000001234
+1234
Example:
#include <stdio.h>
int main()
{
printf("%*.*f\n",5,1,12.34);
printf("%7.4f\n",12.3456);
printf("%f\n",12.3456);
printf("%8.2f\n",12.3456);
printf("%-8.2f\n",12.3456);
printf("%08.2f\n",12.3456);
printf("%10.2e\n",12.3456);
return 0;
}
Output:
12.3
12.3456
12.345600
12.35
12.35
00012.35
1.23e+01

2).Unformated Input Output function:-


These are console Input Output Library function which deal with one character at a time and string
function for Array of characters ( String ) .
The following table show different type of character and string Input Output function .
Data type Function Input / Output
getchar() Input
Character getche() Input
getch() Input
putchar() Output
putch() Output
String gets() Input
puts() Output
1). getchar( ) function :-
This is a un-formatted console Input function which is used to enter one character at a time from a
standard Input device eg. Keyboard . In this the entered character is echoed( display ) on the screen
and the use need to press Enter key .
eg. char alphabet ;
alphabet = getchar() ;
/* In this , firstly we press a key which we want to enter (as say 'A') and we need to press Enter key to
move to the next instruction */
Ex.
main()
{
int i ;
char name[ 5 ] ;
printf(" Enter name \n ") ;
for( i=0 ; i < 5 ; i++ )
{
name[ i ] = getchar() ;
}
}
Output .
Enter name
A < press enter >
B < press enter >
C < press enter >
D < press enter >
E < press enter >

2). getche() function :-


This also comes in the unformatted console Input function which is used to enter ( input ) One
character at a time . In this , the entered character is echoed / displayed on the screen but the user not
need to press Enter key to submit the character . As the key is press , it is accepted from the program .
eg. char alphabet ;
alphabet = getche() ;
/* In this , user only press the character key (say 'A') and is accepted */
Ex.
main()
{
int i ;
char name[ 5 ] ;
printf(" Enter name \n ") ;
for( i=0 ; i < 5 ; i++ )
{
name[ i ] = getche() ;
}
}
3). getch() function :-
This is also unformated console Input function which is used to enter one character at a time . In this ,
the user need neither to press Enter key nor the character is echoed on screen . It is used where the user
not want to show the Input .
eg. char alphabet ;
alphabet = getch() ;
/* In this , we need only to press the character key and it is immediately accepted */
Ex.
main()
{
int i ;
char name[ 5 ] ;
printf(" Enter name \n ") ;
for( i=0 ; i < 5 ; i++ )
{
name[ i ] = getch() ;
}
}
Output .
Enter name
ABCDE < This is your Input , It is not shown on the screen , It is only for your understanding >
4). putchar() function :-
This function is unformatted console Character Output function which is use to print one character (at
a time) on the screen .
eg.
main()
{
char ch ;
printf(" Enter a key ") ;
ch = getch() ;
printf(" \n You have enter character ") ;
putchar( ch ) ;
}
5). putch() function :-
This function is unformatted console Character Output function which is use to print one character (at
a time) on the screen .
eg.
main()
{
char ch ;
printf(" Enter a key ") ;
ch = getch() ;
printf(" \n You have enter character ") ;
putch( ch ) ;
}
(6) gets() function :-
This function is unformatted String Input function . This is used to enter a string ( Array of character )
from standard Input device (such as Keyboard) . The length of entering string is limited from declaring
string length (array) . With this function , the user can enter multiple word in the same time . Let's take
example to describe this point .
Example :- If we want to enter the NAME of a person , we use String for this purpose . As trying this
with scanf() function , we write it as
main()
{
char name[ 15 ] ;
clrscr() ;
printf(" Enter name of 15 Characters ") ;
scanf(" %s " , name ); /* We NOT use & operator for String (Array of characters)*/
getch() ;
}
Output :-
Enter name of 15 Characters HARSIMRAN SINGH
In above example , we use scanf() function to enter characters in string . BUT there is a limitation of
scanf() , that it can only except characters till the user press Enter key or Space-bar key .
so if we try to Enter " HARSIMRAN SINGH "
it only take " HARSIMRAN " as Input and it Ignore the input after space is given . For this reason we
use unformatted string Input function ie. gets() function .
Now we write the above example with gets() .
main()
{
char name[ 15 ] ;
clrscr() ;
printf(" Enter name of 15 Characters ") ;
gets( name ) ; /* Unformatted String Input function */
}
Output .
Enter name of 15 Characters HARSIMRAN SINGH
This take " HARSIMRAN SINGH " as Input .
(7) puts() function :-
This is an Unformatted String Output function . This is used to Print the Content of string on the
standard Output device such as Screen .
Ex.
main()
{
char name[ 15 ] ;
clrscr() ;
puts(" Enter name of 15 Characters ") ;
gets( name ) ; /* String Input */
puts(" The name Entered is ") ;
puts(" name ") ; /* String Output */
getch() ;
}
Output .
Enter name of 15 Characters HARSIMRAN SINGH
The name Entered is HARSIMRAN SINGH
C Operator Precedence Table
This page lists C operators in order of precedence (highest to lowest). Their associativity indicates in
what order operators of equial 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
& 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

C - Operator Types
An operator is a symbol that tells the compiler to perform specific mathematical or
logical manipulations. C language is rich in built-in operators and provides the following types of
operators:
 Arithmetic Operators

 Relational Operators

 Logical Operators

 Bitwise Operators

 Assignment Operators

 Misc Operators

Arithmetic Operators
Following table shows all the arithmetic operators supported by C language. Assume variable A
holds 10 and variable B holds 2 then:

Operator Description Example


+ Adds two operands A + B will give 12
- Subtracts second operand from the first A - B will give 8
* Multiplies both operands A * B will give 20
/ Divides numerator by de-numerator A / B will give 5
% Modulus Operator and remainder of after an integer division B % A will give 2
++ Increments operator increases integer value by one A++ will give 11
-- Decrements operator decreases integer value by one A-- will give 9

Example:
#include <stdio.h>
void main() {
int a,b;
printf("Enter values for a and b");
scanf("%d%d",&a,&b);
printf("sum is =%d",a+b);
printf("difference is =%d",a-b);
printf("multiplication is =%d",a*b);
}
Relational Operators
Following table shows all the relational operators supported by C language. Assume variable A
holds 10 and variable B holds 2, then:

Operator Description Example


Checks if the values of two operands are equal or not, if yes (A == B) is not true.
==
then condition becomes true. Means output will be 0
Checks if the values of two operands are equal or not, if values
!= (A != B) is true. Means
are not equal then condition becomes true.
output will be 1

Checks if the value of left operand is greater than the value of (A > B) is true. Means
>
right operand, if yes then condition becomes true. output will be 1
Checks if the value of left operand is less than the value of right
< (A < B) is not true. Means
operand, if yes then condition becomes true.
output will be 0
Checks if the value of left operand is greater than or equal to the (A >= B) is true.Means
>=
value of right operand, if yes then condition becomes true. output will be 1
Checks if the value of left operand is less than or equal to the
<= (A <= B) is not true. Means
value of right operand, if yes then condition becomes true.
output will be 0

Example:
#include <stdio.h>
void main() {
int a,b;
printf("Enter values for a and b");
scanf("%d%d",&a,&b);
printf("Output is = %d",a==b);
}
Output:
Enter values for a and b2
2
Output is = 1
Logical Operators
Following table shows all the logical operators supported by C language. Assume variable A
holds 1 and variable B holds 0, then:

Operator Description Example


Called Logical AND operator. If both the operands are non- (A && B) is false.
&&
zero, then condition becomes true. Means output will be 0
Called Logical OR Operator. If any of the two operands is non-zero,
|| (A || B) is true. Means
then condition becomes true
output will be 1
Called Logical NOT Operator. Use to reverses the logical state of its !(A && B) is true.
!
operand. If a condition is true then Logical NOT operator will make Means output will be 1
false.
Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^
are as follows:

p q p&q p|q p^q


0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assume if A = 60; and B = 13; now in binary format they will be as follows:
A = 0011 1100
B = 0000 1101
---------------
-- A&B =
0000 1100

A|B = 0011 1101


A^B = 0011 0001
~A = 1100 0011
The Bitwise operators supported by C language are listed in the following table. Assume variable
A holds 60 and variable B holds 13, then:
Operator Description Example
Binary AND Operator copies a bit to the result if it (A & B) will give 12, which is
&
exists in both operands. 0000 1100
Binary OR Operator copies a bit if it exists in either (A | B) will give 61, which is
|
operand. 0011 1101
Binary XOR Operator copies the bit if it is set in one (A ^ B) will give 49, which is
^
operand but not both. 0011 0001
Binary Ones Complement Operator is unary and has the (~A ) will give -61, which is 1100
~
effect of 'flipping' bits. 0011 in 2's complement form.
Binary Left Shift Operator. The left operands value is
A << 2 will give 240 which is
<< moved left by the number of bits specified by the right
1111 0000
operand.
Binary Right Shift Operator. The left operands value is
A >> 2 will give 15 which is 0000
>> moved right by the number of bits specified by the right
1111
operand.

Assignment Operators
There are following assignment operators supported by C language:

Operator Description Example


Simple assignment operator, Assigns values from right C = A + B will assign value of A
=
side operands to left side operand + B into C
Add AND assignment operator, It adds right operand to C += A is equivalent to C = C +
+=
the left operand and assign the result to left operand A
Subtract AND assignment operator, It subtracts right
-= operand from the left operand and assign the result to C -= A is equivalent to C = C - A
left operand
Multiply AND assignment operator, It multiplies right
C *= A is equivalent to C = C *
*= operand with the left operand and assign the result to
A
left operand
Divide AND assignment operator, It divides left
/= operand with the right operand and assign the result to C /= A is equivalent to C = C / A
left operand
Modulus AND assignment operator, It takes modulus C %= A is equivalent to C = C %
%=
using two operands and assign the result to left operand A
<<= Left shift AND assignment operator C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator C &= 2 is same as C = C & 2
^= bitwise exclusive OR and assignment operator C ^= 2 is same as C = C ^ 2
|= bitwise inclusive OR and assignment operator C |= 2 is same as C = C | 2

Misc Operators ↦ sizeof & ternary


There are few other important operators including sizeof and ? : supported by C Language.
Operator Description Example
sizeof() Returns the size of an variable. sizeof(a), where a is integer, will return 4.
& Returns the address of an variable. &a; will give actual address of the variable.
* Pointer to a variable. *a; will pointer to a variable.

If Condition is true ? Then value X : Otherwise value


?: Conditional Expression
Y

Conditional Operators [ ?: ] : Ternary Operator Statement in C


Ternary Operators takes on 3 Arguments

Syntax :

expression 1 ? expression 2 : expression 3

where
→ expression1 is Condition
→ expression2 is Statement Followed if Condition is True
→ expression3 is Statement Followed if Condition is False

Meaning of Syntax :
1. Expression1 is nothing but Boolean Condition i.e it results into either TRUE or FALSE
2. If result of expression1 is TRUE then expression2 is Executed
3. Expression1 is said to be TRUE if its result is NON-ZERO
4. If result of expression1 is FALSE then expression3 is Executed
5. Expression1 is said to be FALSE if its result is ZERO

Operator that works on 3 operands is called as Ternary

operator .
Example:

#include <stdio.h>

void main() {
int m,a,b,c;
printf("Enter values for a, b and c");
scanf("%d%d%d",&a,&b,&c);
m=(a>b?(a>c?a:c):(b>c?b:c));
printf("Largest number is = %d",m);
}
C – Increment/decrement Operators
→ 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–-;

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 incremented before assigning it to variable i.
2 Post increment i++ Value of i is incremented after assigning it to variable i.
3 Pre decrement – –i Value of i is decremented before assigning it to variable i.
4 Post decrement i– – Value of i is decremented after assigning it to variable i.

Precedence of C Operators:
Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator:

For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher
precedenace than + so it first get multiplied with 3*2 and then adds into 7.

Integer and Float Conversions


The rules that are used for the implicit conversion of floating point and integer values in C, are:
 An arithmetic operation between an integer and integer always yields an integer result.
 An operation between a real and real always yields a real result.
 An operation between an integer and real always yields a real result. In this operation
the integer is first promoted to a real and then the operation is performed. Hence the result is
real.
Type Conversion in Assignments
It may so happen that the type of the expression and the type of the variable on the left-hand side
of the assignment operator may not be same. In such a case the value of the expression is
promoted or demoted depending on the type of the variable on left-hand side of =.
It has been assumed that k is an integer variable and a is a real variable.

Type Conversion can be done in two types


1). Automatic Type Conversion (Implicit) 2).Type Casting
(Explicit) (Done from compiler) ( As User need )

Automatic type conversion :-


If in a calculation , Two Operands or variables of different Data-type are present , so the Lower size
data-type is Automatically converted into Higher size data-type before proceeding to calculation .This
automatic conversion is known as implicit type conversion.
The order of size of different data-type variable are shown in table .

If we perform a calculation of two different data type is result in the data-type whose size is greater
among them .
eg.
int and int -----> int
int and float -----> float ( result )
char and int -----> int
char and float -----> float
int and double -----> double
Type Casting :-
We know that Type Conversion are automatically done from compiler , BUT some time we use Type
Casting for avoiding the loss of fractional part also to get desired result . The process of such a local
conversion is known as explicit conversion or casting a value.
The general form of a cast is:
(type- name) expression
eg.
int x = 100 , y = 40 , a ,b ,z ;
float c , d ;
a = x/y ; /* a = 100/40 -----> a = 2 */
c = (float) (x/y) ; /* c = (float) ( 100/40 ) -----> c = 2.500000 */
b = (float) (c*4) ; /* b = 2.5*4 -----> b = 10 */
z = c*4 ; /* z = 2*4 -----> z = 8 */
Arithmetic Expressions
Example:
kk = 3 / 2 * 4 + 3 / 8 + 3
kk = 1 * 4 + 3 / 8 + 3 operation: /
kk = 4 + 3 / 8 + 3 operation: *
kk = 4 + 0 + 3 operation: /
kk = 4 + 3 operation: +
kk = 7 operation: +
Example:
i=2*3/4+4/4+8-2+5/8
i=6/4+4/4+8-2+5/8 operation: *
i=1+4/4+8-2+5/8 operation: /
i = 1 + 1+ 8 - 2 + 5 / 8 operation: /
i=1+1+8-2+0 operation: /
i=2+8-2+0 operation: +
i = 10 - 2 + 0 operation: +
i=8+0 operation : -
i=8 operation: +

TYPES OF VARIABLES DEPENDING UPON PLACE OF DECLARATION


A. Global Variables/External Variables B. Local Variables/Internal Variables

A. Global Variables: also called External Variables


1. The variables that are declared outside all functions are called global variables.
2. Lifetime of these variables is throughout the program.
3. Scope is from the point of declaration to the end of the program.
4. Global variables are automatically initialised to zero, when they are declared.
5. They are allocated space in the global memory section.
6. All the functions can access the global variables after declaration.
7. Global variables can be accessed by other programs e.g. in multifile programs
8. In case a local variable and a global variable, the local variable will have precedence over global variable.

B. Local Variables: or Internal Variables


1. These variables are declared inside a function.
2. Only the function which has the variable declaration can access the local variables.
3. Every function can access only its own local variable, but cann’t access the local variables of other functions.
i.e., variables are protected within function.
4. The local variables are created when the function is invoked and is destroyed when the function is exited.
STORAGE CLASSES:
There are 4 storage classes. A variable in ‘C’ can have any one of the 4 storage classes.
1. Automatic Variables or Local Variables
2. External Variables or Global Variables
3. Static Variables
4. Register Variables

Scope of Variables or Visibility: This refers to those parts of the program where the variable is accessible or
active or visible for use ( e.g. for calculations etc.)

Lifetime of Variable: It refers to the period during which the variable retains the memory location or retains a
given value during execution of a program (i.e. it is alive). Here, the variable can be active or dormant but it is
alive not destroyed.
Storage class tells us: 1) Where the variable is stored. 2) Initial value of the variable. 3) Scope of the
variable. Scope specifies the part of the program which a variable is accessed. 4) Life of the variable.
AUTOMATIC STORAGE CLASS: In this automatic storage class, Variable is stored in memory. Default
value is garbage value Scope is local to the block Life is, with in the block in which the variable is defined
REGISTER STORAGE CLASS: Variable is stored in CPU registers. Default value is garbage value.
Scope is local to the block. Life is,with in the block in which the variable is defined. We can not use register
storage class for all types of variables. For example: register float f;
STATIC STORAGE CLASS: Variable is stored in memory. Default value is zero. Scope is local to the block.
Life is,value of the variable persists between different function calls. Example :
main()
{
add();
add();
}
add()
{
static int i=10;
printf(“ %d”,i);
i+=1;
}
Output:
10 11
EXTERNAL STORAGE CLASS: Variable is stored in memory. Default value is zero. Scope is local to the
block. Life is,as long as the program execution doesn’t come to an end.

Example program for auto variable in C:


The scope of this auto variable is within the function only. It is equivalent to local variable. All local
variables are auto variables by default.
#include<stdio.h>

void increment(void);
int main()
{
increment();
increment();
increment();
increment();
return 0;
}
void increment(void)
{
auto int i = 0 ;
printf ( “%d “, i ) ;
i++;
}

Output:
0000

Example program for static variable in C:


Static variables retain the value of the variable between different function calls.
//C static example

#include<stdio.h>
void increment(void);
int main()
{
increment();
increment();
increment();
increment();
return 0;
}
void increment(void)
{
static int i = 0 ;
printf ( “%d “, i ) ;
i++;
}

Output:
0123

Example program for extern variable in C:


The scope of this extern variable is throughout the main program. It is equivalent to global variable.
Definition for extern variable might be anywhere in the C program.
#include<stdio.h>

int x = 10 ;
int main( )
{
extern int y;
printf(“The value of x is %d \n”,x);
printf(“The value of y is %d”,y);
return 0;
}
int y=50;

Output:
The value of x is 10
The value of y is 50
Example program for register variable in C:
 Register variables are also local variables, but stored in register memory. Whereas, auto
variables are stored in main CPU memory.
 Register variables will be accessed very faster than the normal variables since they are stored
in register memory rather than main memory.
 But, only limited variables can be used as register since register size is very low. (16 bits, 32
bits or 64 bits)
#include <stdio.h>
int main()
{
register int i;
int arr[5];// declaring array
arr[0] = 10;// Initializing array
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
for (i=0;i<5;i++)
{
// Accessing each variable
printf(“value of arr[%d] is %d \n”, i, arr[i]);
}
return 0;
}
Output:
value of arr[0] is 10
value of arr[1] is 20
value of arr[2] is 30
value of arr[3] is 40
value of arr[4] is 50
Summary of the Main Features of the various Storage Classes
Keyword Declaration Statement Declaration Accessibility Existence/ Place of Default
Or Scope Lifetime Storage value
auto auto datatype var_name; Within Accessible Exists from the time of Primary Garbage
function within the invocation of function memory value
or block function or to its return to the
block where calling function OR
it is from the time of entry
declared into the block to the end
of the block.
extern extern datatype var_name; Outside all Accessible Exists as long as the full Primary Zero
functions within the program is in execution. memory
This var has been or within combination
declared somewhere function of program
else as a global or modules that
external variable. form the full
program.
register register datatype var_name; Within a Accessible Exists from the time of CPU Garbage
function within the invocation of function register value
or block function or to its return to the
block where calling function OR
it is from the time of entry
declared into the block to the end
of the block
static static datatype var_name; Within a Internal Internal static: Primary zero
function static: Preserves the value memory
or block Accessible between the function
within the calls or block entries.
function or
block where
static datatype var_name; Outside it is
External External static: Primary zero
all declared
static: Preserves the value in memory
functions Accessible the program file.
within the
program file
where it is
declared and
not other
files.

You might also like