0% found this document useful (0 votes)
16 views30 pages

Module - 2 - CP

Uploaded by

Samuel Johnpeter
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views30 pages

Module - 2 - CP

Uploaded by

Samuel Johnpeter
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 30

MODULE – 2

Basic Elements of C

Introduction: C is a procedural programming language initially developed by Dennis


Ritchie in the year 1972 at Bell Laboratories of AT&T Labs. It was mainly developed as a
system programming language to write the UNIX operating system.
The main features of the C language include:
 General Purpose and Portable
 Low-level Memory Access
 Fast Speed
 Clean Syntax

These features make the C language suitable for system programming like an operating
system or compiler development. C programming is considered as the base for other
programming languages, that is why it is known as mother language.

History of C

There is a close similarity between learning English language and learning C language.
The classical method of learning English is to first learn the alphabets used in the language,
then learn to combine these alphabets to form words, which in turn are combined to form
sentences and sentences are combined to form paragraphs. Learning C is similar and easier.
Instead of straight-away learning how to write programs, we must first know what
alphabets, numbers and special symbols are used in C, then how using them constants,
variables and keywords are constructed, and finally how are these combined to form an
instruction. A group of instructions would be combined later on to form a program.
MODULE – 2

C Character Set
As every language contains a set of characters used to construct words, statements, etc., C language
also has a set of characters which include alphabets, digits, and special symbols. C language supports
a total of 256 characters.

Every C program contains statements. These statements are constructed using words and these
words are constructed using characters from C character set. C language character set contains the
following set of characters...

1. Alphabets
2. Digits
3. Special Symbols
4. White space

1. Alphabets:

C language supports all the alphabets from the English language. Lower and upper case letters
together support 52 alphabets.

lower case letters - a to z

UPPER CASE LETTERS - A to Z

2. Digits:

C language supports 10 digits which are used to construct numerical values in C language.

Digits - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

3. Special Symbols:

C language supports a rich set of special symbols that include symbols to perform mathematical
operations, to check conditions and other special symbols.

Special Symbols - ~ @ # $ % ^ & * ( ) _ - + = { } [ ] ; : ' " / ? . > , < \ |


MODULE – 2

Special ASCII Special ASCII


Character Code Character Code
~ 126 – 45
! 33 _ 95
@ 64 + 43
# 35 = 61
$ 36 { 123
% 37 } 125
& 38 | 124
* 42 \ 92
( 40 ; 58
) 41 : 59
‘ 39 / 47
“ 34 ? 63
< 60 > 62

4. White space

In computer programming, white space is a character that represent vertical space.


White space \b,\v,\? and so on.

White Space Meaning White Space Meaning


\b blank space \\ back slash
\t horizontal tab \’ single quote
\v vertical tab \” double quote
\r carriage return \? Question mark
\f form feed \0 null
\n new line \a alarm (bell

Structure of the C Program


The basic structure of a C program is divided into 6 parts which makes it easy to read,
modify, document, and understand in a particular format. C program must follow the
below-mentioned outline in order to successfully compile and execute. Debugging is
easier in a well-structured C program.
Sections of the C Program
There are 6 basic sections responsible for the proper execution of a program. Sections are
mentioned below:
1. Documentation
2. Preprocessor Section
3. Definition
4. Global Declaration
5. Main() Function
6. Sub Programs
MODULE – 2

1. Documentation
This section consists of the description of the program, the name of the program, and the
creation date and time of the program. It is specified at the start of the program in the
form of comments. Documentation can be represented as:
// description, name of the program, programmer name, date, time etc.
or
/*
description, name of the program, programmer name, date, time etc.
*/
Anything written as comments will be treated as documentation of the program and this
will not interfere with the given code. Basically, it gives an overview to the reader of the
program.

2. Preprocessor Section
All the header files of the program will be declared in the preprocessor section of the
program. Header files help us to access other’s improved code into our code. A copy of
these multiple files is inserted into our program before the process of compilation.
Example:
#include<stdio.h>
#include<math.h>

3. Definition
Preprocessors are the programs that process our source code before the process of
compilation. There are multiple steps which are involved in the writing and execution of
the program. Preprocessor directives start with the ‘#’ symbol. The #define preprocessor
MODULE – 2

is used to create a constant throughout the program. Whenever this name is encountered
by the compiler, it is replaced by the actual piece of defined code.
Example:
#define long long ll

4. Global Declaration
The global declaration section contains global variables, function declaration, and static
variables. Variables and functions which are declared in this scope can be used anywhere
in the program.
Example:
int num = 18;

5. Main() Function
Every C program must have a main function. The main() function of the program is written
in this section. Operations like declaration and execution are performed inside the curly
braces of the main program. The return type of the main() function can be int as well as
void too. void() main tells the compiler that the program will not return any value. The int
main() tells the compiler that the program will return an integer value.
Example:
void main()
or
int main()

6. Sub Programs
User-defined functions are called in this section of the program. The control of the
program is shifted to the called function whenever they are called from the main or
outside the main() function. These are specified as per the requirements of the
programmer.
Example:
int sum(int x, int y)
{
return x+y;
}

First C Program
#include <stdio.h>
int main(){
printf("Hello C Language");
return 0;
}
MODULE – 2

Creating and Running C Program


Generally, the programs created using programming languages like C, C++, Java, etc., are
written using a high-level language like English. But, the computer cannot understand the
high-level language. It can understand only low-level language. So, the program written in
the high-level language needs to be converted into the low-level language to make it
understandable for the computer. This conversion is performed using either Interpreter or
Compiler.
To create and execute C programs in the Windows Operating System, we need to install
Turbo C software. We use the following steps to create and execute C programs in Windows
OS…

Step 1: Creating a Source Code

Source code is a file with C programming instructions in a high-level language. To create


source code, we use any text editor to write the program instructions. The instructions
written in the source code must follow the C programming language rules. The following
steps are used to create a source code file in Windows OS…

 Click on the Start button


 Select Run
 Type cmd and press Enter
 Type cd c:\TC\bin in the command prompt and press Enter
 Type TC press Enter
 Click on File -> New in C Editor window
 Type the program
 Save it as FileName.c (Use shortcut key F2 to save)

Step 2: Compile Source Code (Alt + F9)

The compilation is the process of converting high-level language instructions into low-level
language instructions. We use the shortcut key Alt + F9 to compile a C program in Turbo C.
MODULE – 2

The compilation is the process of converting high-level language instructions into low-
level language instructions.

Whenever we press Alt + F9, the source file is going to be submitted to the Compiler. On
receiving a source file, the compiler first checks for the Errors. If there are any Errors then
compiler returns List of Errors, if there are no errors then the source code is converted
into object code and stores it as a file with .obj extension. Then the object code is given to
the Linker. The Linker combines both the object code and specified header file code and
generates an Executable file with a .exe extension.

Step 3: Executing / Running Executable File (Ctrl + F9)

After completing compilation successfully, an executable file is created with


a .exe extension. The processor can understand this .exe file content so that it can perform
the task specified in the source file.

We use a shortcut key Ctrl + F9 to run a C program. Whenever we press Ctrl + F9,
the .exe file is submitted to the CPU. On receiving .exe file, CPU performs the task according
to the instruction written in the file. The result generated from the execution is placed in a
window called User Screen.

Step 4: Check Result (Alt + F5)

After running the program, the result is placed into User Screen. Just we need to open the
User Screen to check the result of the program execution. We use the shortcut key Alt +
F5 to open the User Screen and check the result.

C Language Components:
The four main components of C Language are

1. The Character Set


2. Tokens
3. Variables
4. Data Types
1. The Character Set: Character set is a set of valid characters that a language can
recognizes. A character represents any letter, digits or any sign.
a. Letters : A-Z, a-z
b. Digits : 0 – 9
c. Special Symbols : /,*,@,#,$, etc..
2. Tokens:

A token in C can be defined as the smallest individual element of the C programming


language that is meaningful to the compiler. It is the basic component of a C program.
MODULE – 2

Types of Tokens in C
The tokens of C language can be classified into six types based on the functions they are
used to perform. The types of C tokens are as follows:
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators

1. C Token – Keywords
The keywords are pre-defined or reserved words in a programming language. Each
keyword is meant to perform a specific function in a program. Since keywords are referred
names for a compiler, they can’t be used as variable names because by doing so, we are
trying to assign a new meaning to the keyword which is not allowed. You cannot redefine
keywords. However, you can specify the text to be substituted for keywords before
compilation by using C preprocessor directives. C language supports 32 keywords which
are given below:
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

2. C Token – Identifiers
Identifiers are used as the general terminology for the naming of variables, functions, and
arrays. These are user-defined names consisting of an arbitrarily long sequence of letters
and digits with either a letter or the underscore(_) as a first character. Identifier names
must differ in spelling and case from any keywords. You cannot use keywords as
identifiers; they are reserved for special use. Once declared, you can use the identifier in
later program statements to refer to the associated value. A special identifier called a
statement label can be used in goto statements.
Rules for Naming Identifiers
Certain rules should be followed while naming c identifiers which are as follows:
 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 the first 31 characters are significant.
Note: Identifiers are case-sensitive so names like variable and Variable will be treated as
different.
MODULE – 2

For example,
 main: method name.
 a: variable name.

3. Constants:
A constant is a fixed value. It doesn’t change its value during the execution of the program.
The following are various types of constants.
 Integer Constants
 Floating Point Constants
 Single Character Constants
 String Constants
Integer constants: Any number without fractional part is called an integer constant. The
integer numbers can contain digits (0…9) and sign (+ or -). An integer constant must not
contain commas and spaces. Integers can be decimal, octal or hexa-decimal.
Ex: 3 -3 15 -15 2500 -9700 etc.  Decimal Integers
03 0123 etc.  Octal Integers
0x3 0x123 etc.  Hexa-Decimal Integers
Floating Point (Real) Constants:
Floating point constants are also called real constants. A floating point number can contain
digits (0…9), a decimal point and/or exponent. The letter ‘E’ or ‘e’ represents the exponent.
Ex: 45.0 4520.2587 -6847.000 -74.56000 etc.
The exponent format (‘e’ notation) can be used to represent very small or large number.
Ex: 6.5E5 or 6.5E+5 means 6.5x105
6.5E-5 means 6.5x10-5
Single Character Constants:
A single character constant contains only one character enclosed within single quotes. It
may contain any alphabet, digit or special symbol. It can be used for arithmetic operations.
However, its ASCII value is used in arithmetic operation.
Ex: ‘A’ ‘h’ ‘4’ ‘+’ ‘&’ etc.
String Constants:
A string constant is a sequence of one or more characters enclosed within double quotes. It
can contain alphabets, digits or special symbols.
Ex: “A” “ABCDE” “%d” “Result = %d” etc.
MODULE – 2
MODULE – 2

Variable
A variable in C is a memory location with some name that helps store some form of data
and retrieves it when required. We can store different types of data in the variable and
reuse the same variable for storing some other data any number of times.
C Variable Syntax
The syntax to declare a variable in C specifies the name and the type of the variable.

data_type variable_name = value; // defining single variable


or
data_type variable_name1, variable_name2; // defining multiple variable

 data_type: Type of data that a variable can store.


 variable_name: Name of the variable given by the user.
 value: value assigned to the variable by the user.
Example
int var; // integer variable
char a; // character variable
float fff; // float variables

There are 3 aspects of defining a variable:


1. Variable Declaration
2. Variable Definition
3. Variable Initialization

1. C Variable Declaration
Variable declaration in C tells the compiler about the existence of the variable with the
given name and data type. When the variable is declared compiler automatically allocates
the memory for it.

2. C Variable Definition
In the definition of a C variable, the compiler allocates some memory and some value to it.
A defined variable will contain some random garbage value till it is not initialized.
Example
int var;
char var2;
MODULE – 2

3. C Variable Initialization
Initialization of a variable is the process where the user assigns some meaningful value to
the variable.
Example
int var; // variable definition
var = 10; // initialization
or
int var = 10; // variable declaration and definition

Rules for Naming Variables in C


You can assign any name to the variable as long as it follows the following rules:
1. A variable name must only contain alphabets, digits, and underscore.
2. A variable name must start with an alphabet or an underscore only. It cannot start
with a digit.
3. No whitespace is allowed within the variable name.
4. A variable name must not be any reserved word or keyword.

Types of Variables in C

There are many types of variables in c:

1. local variable
2. global variable
3. static variable
4. automatic variable
5. external variable

Local Variable

A variable that is declared inside the function or block is called a local variable.

It must be declared at the start of the block.

void function1(){
int x=10;//local variable
}

You must have to initialize the local variable before it is used.

Global Variable

A variable that is declared outside the function or block is called a global variable. Any
function can change the value of the global variable. It is available to all the functions.
MODULE – 2

It must be declared at the start of the block.

int value=20;//global variable


void function1(){
int x=10;//local variable
}
Static Variable

A variable that is declared with the static keyword is called static variable.

It retains its value between multiple function calls.

void function1(){
int x=10;//local variable
static int y=10;//static variable
x=x+1;
y=y+1;
printf("%d,%d",x,y);
}

If you call this function many times, the local variable will print the same value for each
function call, e.g, 11,11,11 and so on. But the static variable will print the incremented
value in each function call, e.g. 11, 12, 13 and so on.

Automatic Variable

All variables in C that are declared inside the block, are automatic variables by default.
We can explicitly declare an automatic variable using auto keyword.

void main(){
int x=10;//local variable (also automatic)
auto int y=20;//automatic variable
}
External Variable

We can share a variable in multiple C source files by using an external variable. To


declare an external variable, you need to use extern keyword.

myfile.h

extern int x=10;//external variable (also global)


program1.c
MODULE – 2

#include "myfile.h"
#include <stdio.h>
void printValue(){
printf("Global variable: %d", global_variable);
}

Data Types in C
Each variable in C has an associated data type. It specifies the type of data that the
variable can store like integer, character, floating, double, etc. Each data type requires
different amounts of memory and has some specific operations which can be performed
over it. The data type is a collection of data with values having fixed values, meaning as
well as its characteristics.

Type Storage size Value range


Char 1 byte -128 to 127 or 0 to 255
unsigned char 1 byte 0 to 255
signed char 1 byte -128 to 127
Int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647
unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295
Short 2 bytes -32,768 to 32,767
unsigned short 2 bytes 0 to 65,535
MODULE – 2

Long 4 bytes -2,147,483,648 to 2,147,483,647


unsigned long 4 bytes 0 to 4,294,967,295
Type Storage size Value range Precision
Float 4 byte 1.2E-38 to 3.4E+38 6 decimal places
Double 8 byte 2.3E-308 to 1.7E+308 15 decimal places
long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal places

Primitive data types in C:

Integer Data Type:


The integer datatype in C is used to store the integer numbers (any number including
positive, negative and zero without decimal part). Octal values, hexadecimal values, and
decimal values can be stored in int data type in C.
 Range: -2,147,483,648 to 2,147,483,647
 Size: 4 bytes
 Format Specifier: %d
Syntax of Integer
int var_name;

The integer data type can also be used as


1. unsigned int: Unsigned int data type in C is used to store the data values from zero to
positive numbers but it can’t store negative values like signed int.
2. short int: It is lesser in size than the int by 2 bytes so can only store values from -
32,768 to 32,767.
3. long int: Larger version of the int datatype so can store values greater than int.
4. unsigned short int: Similar in relationship with short int as unsigned int with int.

Character Data Type:


Character data type allows its variable to store only a single character. The size of the
character is 1 byte. It is the most basic data type in C. It stores a single character and
requires a single byte of memory in almost all compilers.
 Range: (-128 to 127) or (0 to 255)
 Size: 1 byte
 Format Specifier: %c
Syntax of char
The char keyword is used to declare the variable of character type:
char var_name;

Float Data Type:


In C programming float data type is used to store floating-point values. Float in C is used to
store decimal and exponential values. It is used to store decimal numbers (numbers with
floating point values) with single precision.
 Range: 1.2E-38 to 3.4E+38
MODULE – 2

 Size: 4 bytes
 Format Specifier: %f
Syntax of float
The float keyword is used to declare the variable as a floating point:
float var_name;

Double Data Type


A Double data type in C is used to store decimal numbers (numbers with floating point
values) with double precision. It is used to define numeric values which hold numbers with
decimal values in C.
The double data type is basically a precision sort of data type that is capable of holding 64
bits of decimal numbers or floating points. Since double has more precision as compared
to that float then it is much more obvious that it occupies twice the memory occupied by
the floating-point type. It can easily accommodate about 16 to 17 digits after or before a
decimal point.

 Range: 1.7E-308 to 1.7E+308


 Size: 8 bytes
 Format Specifier: %lf

Syntax of Double
The variable can be declared as double precision floating point using the
double keyword:
double var_name;

Void Data Type


The void data type in C is used to specify that no value is present. It does not provide a
result value to its caller. It has no values and no operations. It is used to represent
nothing. Void is used in multiple ways as function return type, function arguments as void,
and pointers to void.

Syntax:
// function return type void
void exit(int check);
// Function without any parameter can accept void.
int print(void);

Size of Data Types in C:


The size of the data types in C is dependent on the size of the architecture, so we cannot
define the universal size of the data types. For that, the C language provides the sizeof()
operator to check the size of the data types.
Example
#include <stdio.h>
int main()
MODULE – 2

{
int size_of_int = sizeof(int);
int size_of_char = sizeof(char);
int size_of_float = sizeof(float);
int size_of_double = sizeof(double);

printf("The size of int data type : %d\n", size_of_int);


printf("The size of char data type : %d\n",size_of_char);
printf("The size of float data type : %d\n",size_of_float);
printf("The size of double data type : %d",size_of_double);

return 0;
}

C Input Output Statements


In C Language input and output function are available as C compiler functions or C libraries
provided with each C compiler implementation. These all functions are collectively known
as Standard I/O Library function.
As all the input/output statements deals with the console, so these are also Console
Input/Output functions. Console Input/Output function access the three major files before
the execution of a C Program. These are as follows:

 stdin: This file is used to receive the input (usually is keyborad file, but can also take
input from the disk file).
 stdout: This file is used to send or direct the output (usually is a monitor file, but can
also send the output to a disk file or any other device).
 stderr: This file is used to display or store error messages.

Input Ouput Statement


MODULE – 2

Input and Output statement are used to read and write the data in C programming. These
are embedded in stdio.h (standard Input/Output header file).

Input means to provide the program with some data to be used in the program
and Output means to display data on screen or write the data to a printer or a file.C
programming language provides many built-in functions to read any given input and to
display data on screen when there is a need to output the result.

There are mainly two of Input/Output functions are used for this purpose. These are
discussed as:

 Unformatted I/O functions


 Formatted I/O functions

Unformatted I/O functions


There are mainly six unformatted I/O functions discussed as follows:

 getchar()
 putchar()
 gets()
 puts()
 getch()
 getche()

Formatted I/O functions


Formatted I/O functions which refers to an Input or Ouput data that has been arranged in a
particular format. There are mainly two formatted I/O functions discussed as follows:

 scanf()
 printf()

scanf()

The scanf() function is an input function. It used to read the mixed type of data from
keyboard. You can read integer, float and character data by using its control codes or format
codes. The general syntax is as:

scanf("control strings",arg1,arg2,..............argn);
or

scanf("control strings",&v1,&v2,&v3,................&vn);
MODULE – 2

Where arg1,arg2,……….argn are the arguments for reading and v1,v2,v3,……..vn all are the
variables.

The scanf() format code (spedifier) is as shown in the below table:

Format Code Meaning

%c To read a single character

%d To read a signed decimal integer (short)

%ld To read a signed long decimal integer

%e To read a float value exponential

%f To read a float (short0 or a single precision value

%lf To read a double precision float value

%g To read double float value

%h To read short integer

%i To read an integer (decimal, octal, hexadecimal)

%o To read an octal integer only

%x To read a hexadecimal integer only

%u To read unsigned decimal integer (used in pointer)

%s To read a string

%[..] To read a string of words from the defined range

%[^] To read string of words which are not from the defined range

printf()

This ia an output function. It is used to display a text message and to display the mixed type
(int, float, char) of data on screen. The general syntax is as:

printf("control strings",&v1,&v2,&v3,................&vn);
or

printf("Message line or text line");


MODULE – 2

Where v1,v2,v3,……..vn all are the variables.

The control strings use some printf() format codes or format specifiers or conversion
characters. These all are discussed in the below table as:

FORAMAT Code Meaning

%c To read a single character

%s To read a string

%d To read a signed decimal integer (short)

%ld To read a signed long decimal integer

%f To read a float (short0 or a single precision value

%lf To read a double precision float value

%e To read a float value exponential

%g To read double float value

%o To read an octal integer only

%x To read a hexadecimal integer only

%u To read unsigned decimal integer (used in pointer)

C Operators
 The C language supports a rich set of built-in operators.
 An operator is a symbol that tells the compiler to perform a certain operation
(arithmetic, comparison, etc.) using the values provided along with the operator.
 Operators are used in programs to manipulate data and variables.

What is an Operand?
 Every operator works with some values.

 The value with which an operator works is called as Operand.

 For example, when we say 4+5, numbers 4 and 5 are operands whereas + is an
operator.
MODULE – 2

 Different operators work with different numbers of operands like the + operator
requires two operands or values, the increment operator ++ requires a single
operand.

An operator is a symbol used to perform arithmetic and logical operations. It is used to


manipulate data stored in the variables.
‘C’ language has the following types of operators.
1. Arithmetic operators
2. Increment and decrement operators
3. Assignment operators
4. Relational operators
5. Logical operators
6. Conditional or Ternary operator
7. Bitwise operators
8. Special operators

1. Arithmetic Operators

These operators help perform primary arithmetic operations like multiplying, dividing,
adding, subtracting, finding modulus, etc.

NAME OPERATOR OPERAND OPERATION

Addition + x,y x+y; adds two numbers

Subtraction x,y x-y; subtracts one number from


another

Multiplication * x,y x*y; returns the product of two


numbers

Division / x,y x/y; returns the quotient when two


numbers are divided

Modulus % x,y x%y; returns the remainder when


two numbers are divided

2. Decrement and Increment Operators

These operators are useful in minimizing calculation. n=n+1 can be truncated to n++. The
operators are:

1. Increment (++)
MODULE – 2

2. Decrement (–)
There is a significant difference in usage of the operators depending on the place of
application.

1. Pre-increment operators: if we write the ++ operator before the variable name, one
is added to the operand, and after that, the result is assigned to the variable.
2. Post-increment operators: if we write the ++ operator after the variable name, the
value is first assigned to the variable, and increment by 1 occurs.

3. Assignment Operators

We use these operators to assign specific values to variables.

OPERATOR NAME USE

= Assignment Assigns value from right to left


operand

+= Addition assignment Stores summed value in the left


operand

-= Subtraction Stores subtracted value in the left


assignment operand

*= Multiplication Stores multiplied value in the left


assignment operand

/= Division assignment Stores quotient in the left


operand

%= Modulus assignment Stores remainder in the left


operand

4. Relational Operators

Relational operators are used for comparing two values of quantities with each other. It
establishes a relation between two values.

NAME OPERATOR USAGE


MODULE – 2

Equal to == Checks whether the two operand values are equal

Not equal to != Checks whether the two operand variables or


constants are not equal to each other

Lesser than <= Checks if one value is lesser than or equal to the
equal to other one

Greater than >= Checks if one of the values is greater than or equal
equal to to another one

Lesser than < Checks whether one operand is lesser than the
other one

Greater than > Checks whether one parent is greater than the
other one

5. Logical Operators
The logical operators are the symbols that are used to combine multiple conditions into one
condition. The following table provides information about logical operators.

Operator Meaning Example

&& Logical AND - Returns TRUE if all conditions are TRUE 10 < 5 && 12 > 10 is
otherwise returns FALSE FALSE

|| Logical OR - Returns FALSE if all conditions are FALSE 10 < 5 || 12 > 10 is TRUE
otherwise returns TRUE

! Logical NOT - Returns TRUE if condition is FLASE and !(10 < 5 && 12 > 10) is
returns FALSE if it is TRUE TRUE

6. Conditional Operator

Conditional operator or ternary operator reduces the work of an if-else block 21 single
statement. It is constructed for conditional expressions.
MODULE – 2

Syntax:
VariableName = (condition) ? TrueValue : FalseValue;
Example:
a= (b>c) ? (b+c) : (b-c);

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


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

Operator Meaning Example

⇒ 16 (10000)
& the result of Bitwise AND is 1 if all the bits are 1 A&B
otherwise it is 0

⇒ 29 (11101)
| the result of Bitwise OR is 0 if all the bits are 0 A|B
otherwise it is 1

⇒ 13 (01101)
^ the result of Bitwise XOR is 0 if all the bits are same A^B
otherwise it is 1

⇒ 6 (00110)
~ the result of Bitwise once complement is negation of ~A
the bit (Flipping)

⇒ 100 (1100100)
<< the Bitwise left shift operator shifts all the bits to the A << 2
left by the specified number of positions

⇒ 6 (00110)
>> the Bitwise right shift operator shifts all the bits to the A >> 2
right by the specified number of positions

8. Special Operators (sizeof, pointer, comma, dot, etc.)


The following are the special operators in c programming language.

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

sizeof(variableName);

Pointer operator (*)


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

Comma operator (,)


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

Dot operator (.)


This operator is used to access members of structure or union.
MODULE – 2

EXPRESSIONS

An expression is a collection of operands joined together by certain operator that represent


a value. There are two types of expressions.
They are
1. Arithmetic or Numeric Expression
2. Relational or Boolean Expression
Arithmetic Expression:
When an expression uses arithmetic operators then it is called arithmetic or numeric
expression. An arithmetic or numeric expression always represents numeric value.
1. Two successive operators are not permitted. However, the space(s) or parenthesis
can be used to separate two successive operators.
Example: a*-25 is invalid, a*(-25) is valid
2. Arithmetic operations cannot be implied. It means, no operator is assumed to be
present.
Example: a = bc+d(x+y+z) is invalid
a = b*c+d*(x+y+z) is valid.
3. The evaluation of an arithmetic expression follows the precedence order of
operators. For example: 5+2*5 gives 15 and (5+2)*5 gives 35
4. There cannot be imbalance of parenthesis. The number of left parenthesis must be
equal to the number of right parenthesis.
5. The arithmetic operation between two integers gives integer result. It is Integer
mode expression. Example: 5/2 gives 2
6. The arithmetic operation between two float values gives float result. It is real mode
expression Example: 5.0 / 2.0 gives 2.5
7. The arithmetic operation between an integer and a float value gives float result. It is
mixed mode expression.
Example: 5 / 2.0 gives 2.5
8. The arithmetic operation can be performed between integer and character
datatypes
Example: ‘A’+30 gives 95

Relational or Boolean Expression:


When an expression uses relational and logical operators then it is called relational
expression. A relational expression is also known as condition or logical expression. This
expression gives the result either true (1) or false (0).
Examples:
 a>b
 salary <= 5000
 x==0
 (a>b¦ ¦a>c)
MODULE – 2

 ((avg >= 50) && (avg <= 75))


OPERATOR PRECEDENCE

Operator precedence determines the grouping of terms in an expression and decides how
an expression is evaluated. Certain operators have higher precedence than others; for
example, the multiplication operator has a higher precedence than the addition operator.

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

Here, operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom. Within an expression, higher precedence operators will be
evaluated first.

Category Operator Associativity

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

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

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right


MODULE – 2
MODULE – 2

Evolution of operators in an expression is as follows:


 An expression will be evaluated based on the priority of operators. Example:
5+3*2
 In the above expression, there are two operators (+ and *) in which * has high
priority. So the operator * is evaluated first and then + is evaluated. Hence the result
is 11.
 If an expression has equal priority operators then the expression is evaluated
based on the associativity.
 Example: 5+3–2
 In the above expression, the operators ‘+’ and ‘–’ have equal priority. Their
associativity is left to right. So first “+” is evaluated and then ‘–’ is evaluated. Hence
the result is 6.
 In case, if we want to change priority order then we can put an expression within
parenthesis. Example: (5+3)*2 gives the result 16

Example: x=3*2/2+3/2+2–2+3*2
=6/2+3/2+2–2+3*2
=3+3/2+2–2+3*2
=3+1+2–2+3*2
=4+2–2+6
=6–2+6
=4+6
= 10
C- TypeCasting
Typecasting in C is the process of converting one data type to another data type by the
programmer using the casting operator during program design.
In typecasting, the destination data type may be smaller than the source data type when
converting the data type to another data type, that’s why it is also called narrowing
conversion.
Example :
int x;
float y;
y = (float) x;
Types of Type Casting in C
In C there are two major types to perform type casting.

1. Implicit type casting


2. Explicit type casting
MODULE – 2

1. Implicit Type Casting


Implicit type casting in C is used to convert the data type of any variable without using the
actual value that the variable holds. It performs the conversions without altering any of the
values which are stored in the data variable. Conversion of lower data type to higher data
type will occur automatically.
Integer promotion will be performed first by the compiler. After that, it will determine
whether two of the operands have different data types. Using the hierarchy below, the
conversion would appear as follows if they both have varied data types:

2. Explicit Type Casting


There are some cases where if the datatype remains unchanged, it can give incorrect
output. In such cases, typecasting can help to get the correct output and reduce the time of
compilation. In explicit type casting, we have to force the conversion between data types.
This type of casting is explicitly defined within the program.
#include <stdio.h>
// Driver Code
int main()
{
int a = 15, b = 2;
double div;

// Explicit Typecasting in double


div = (double)a / b;
printf("The result of Explicit typecasting is %f", div);
return 0;
}

You might also like