0% found this document useful (0 votes)
69 views34 pages

Units Cost Accounting Pankaj and The Reserve Bank of India

Uploaded by

saniyasanu0412
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)
69 views34 pages

Units Cost Accounting Pankaj and The Reserve Bank of India

Uploaded by

saniyasanu0412
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/ 34

UNIT-1

Introduction to C

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


developed in 1972 by Dennis M. Ritchie at the Bell Telephone Laboratories to develop the
UNIX operating system. C is the most widely used computer language.

Dennis Ritchie further was referred as “The Father of Modern Programming


Languages”.

C programming is considered as the base for other programming languages, that is why it is
known as mother language.

It can be defined by the following ways:

1. Mother language

2. System programming language

3. Procedure-oriented programming language

4. Structured programming language

5. Mid-level programming language

1) C as a mother language

C language is considered as the mother language of all the modern programming languages
because most of the compilers, JVMs, Kernels, etc. are written in C language, and most of
the programming languages follow C syntax, for example, C++, Java, C#, etc.

It provides the core concepts like the array, strings, functions, file handling, etc. that are being
used in many languages like C++, Java, C#, etc.

2) C as a system programming language

A system programming language is used to create system software. C language is a system


programming language because it can be used to do low-level programming (for example
driver and kernel). It is generally used to create hardware devices, OS, drivers, kernels, etc.
For example, Linux kernel is written in C.

It can't be used for internet programming like Java, .Net, PHP, etc.
3) C as a procedural language

A procedure is known as a function, method, routine, subroutine, etc. A procedural


language specifies a series of steps for the program to solve the problem.

A procedural language breaks the program into functions, data structures, etc.

C is a procedural language. In C, variables and function prototypes must be declared before


being used.

4) C as a structured programming language

A structured programming language is a subset of the procedural language. Structure means to


break a program into parts or blocks so that it may be easy to understand.

In the C language, we break the program into parts using functions. It makes the program easier
to understand and modify.

5) C as a mid-level programming language

C is considered as a middle-level language because it supports the feature of both low-level


and high-level languages. C language program is converted into assembly code, it supports
pointer arithmetic (low-level), but it is machine independent (a feature of high-level).

A Low-level language is specific to one machine, i.e., machine dependent. It is machine


dependent, fast to run. But it is not easy to understand.

A High-Level language is not specific to one machine, i.e., machine independent. It is easy to
understand.

C Program

all C programs are given with C compiler so that you can quickly change the C program code.
File: main.c
1. #include <stdio.h>
2. int main() {
3. printf("Hello C Programming\n");
4. return 0;
5. }
Features of C Language

C is the widely used language. It provides many features that are given below.

1. Simple
2. Machine Independent or Portable
3. Mid-level programming language
4. structured programming language
5. Rich Library
6. Memory Management
7. Fast Speed
8. Pointers
9. Recursion
10. Extensible
1) Simple

C is a simple language in the sense that it provides a structured approach (to break the
problem into parts), the rich set of library functions, data types, etc.

2) Machine Independent or Portable

Unlike assembly language, c programs can be executed on different machines with some
machine specific changes. Therefore, C is a machine independent language.

3) Mid-level programming language

Although, C is intended to do low-level programming. It is used to develop system


applications such as kernel, driver, etc. It also supports the features of a high-level language.
That is why it is known as mid-level language.
4) Structured programming language

C is a structured programming language in the sense that we can break the program into
parts using functions. So, it is easy to understand and modify. Functions also provide code
reusability.

5) Rich Library

C provides a lot of inbuilt functions that make the development fast.

6) Memory Management

It supports the feature of dynamic memory allocation. In C language, we can free the
allocated memory at any time by calling the free() function.

7) Speed

The compilation and execution time of C language is fast since there are lesser inbuilt functions
and hence the lesser overhead.

8) Pointer

C provides the feature of pointers. We can directly interact with the memory by using the
pointers. We can use pointers for memory, structures, functions, array, etc.

9) Recursion

In C, we can call the function within the function. It provides code reusability for every
function. Recursion enables us to use the approach of backtracking.

10) Extensible

C language is extensible because it can easily adopt new features.


Applications of C Programming
C was initially used for system development work, particularly 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 the code written in assembly language. Some examples of the use of
C are -
 Operating Systems
 Language Compilers
 Assemblers
 Text Editors
 Print Spoolers
 Network Drivers
 Modern Programs
 Databases
 Language Interpreters
 Utilities

History of C:

C Programming history:-

 In 1960, ALGOL was developed by the international group.


 In 1966, Martin Richards developed BCPL (Basic Combined Programming Language
before developing C.
 Later, Ken Thomson further developed BCPL by developing the first letter of BCPL
i.e. he developed the B language.
 Ken Thomson developed BASIC type of UNIX Operating System, while the B language
was in motion.
 After all this, by further developing the B language, Dennis Ritchie developed the C
language in the Bell laboratory.
 After developing the C language, Dennis Ritchie and Ken Thompson together
developed the UNIX Operating System.
 In 1978, Kerni Ghan and Ritchie both did further improvement in C language and they
brought the C programming language in front of the whole world.
 In 1989, ANSI C developed by the ANSI Committee.
 In 1999, the new version of C was developed, in which have new features like Data
Types- char, float, int, double was used.
 Today’s we are using the new version of C is C11, which is developed by Standard
Committee.

Basic Structure Of C Program

Any C program is consists of 6 main sections. Below you will find brief explanation of each of
them.

Basic Structure of C Program


Documentation Section
This section consists of comment lines which include the name of programmer, the
author and other details like time and date of writing the program. Documentation section helps
anyone to get an overview of the program.

EXAMPLE:
Single Line Comment : // Comments
Multiline Comments: /* ---------------- */
Link Section
The link section consists of the header files of the functions that are used in the
program. It provides instructions to the compiler to link functions from the system library.
Example:
#include<stdio.h>
#include<math.h>
#define
Definition Section
All the symbolic constants are written in definition section. Macros are known as
symbolic constants.
Example:
// calculating sum
sum = a + b;
Global Declaration Section
The global variables that can be used anywhere in the program are declared in global
declaration section. This section also declares the user defined functions.
Examples:
int a = 5;
float num = 2.54;
char ch ='z';

main() Function Section


It is necessary have one main() function section in every C program. This section
contains two parts, declaration and executable part.
The declaration part declares all the variables that are used in executable part. These two
parts must be written in between the opening and closing braces. Each statement in the
declaration and executable part must end with a semicolon (;). The execution of program starts
at opening braces and ends at closing braces.
Example:
void Main()
int main()
Subprogram Section
The subprogram section contains all the user defined functions that are used to perform
a specific task. These user defined functions are called in the main() function.

Example:
/* Sum of two numbers */
#include<stdio.h>
int main()
{
int a, b, sum;
printf("Enter two numbers to be added ");
scanf("%d %d", &a, &b);
// calculating sum
sum = a + b;
printf("%d + %d = %d", a, b, sum);
return 0; // return the integer value in the sum
}
Algorithm:
Algorithm is a step-by-step procedure, which defines a set of instructions to be executed in a
certain order to get the desired output. Algorithms are generally created independent of
underlying languages, i.e. an algorithm can be implemented in more than one programming
language.

From the data structure point of view, following are some important categories of algorithms −

 Search − Algorithm to search an item in a data structure.


 Sort − Algorithm to sort items in a certain order.
 Insert − Algorithm to insert item in a data structure.
 Update − Algorithm to update an existing item in a data structure.
 Delete − Algorithm to delete an existing item from a data structure.

Characteristics of an Algorithm
Not all procedures can be called an algorithm. An algorithm should have the following
characteristics −

 Unambiguous − Algorithm should be clear and unambiguous. Each of its steps (or
phases), and their inputs/outputs should be clear and must lead to only one meaning.
 Input − An algorithm should have 0 or more well-defined inputs.
 Output − An algorithm should have 1 or more well-defined outputs, and should match
the desired output.
 Finiteness − Algorithms must terminate after a finite number of steps.
 Feasibility − Should be feasible with the available resources.
 Independent − An algorithm should have step-by-step directions, which should be
independent of any programming code.

Example
Problem − Design an algorithm to add two numbers and display the result.
Step 1 − START
Step 2 − declare three integers a, b & c
Step 3 − define values of a & b
Step 4 − add values of a & b
Step 5 − store output of step 4 to c
Step 6 − print c
Step 7 − STOP
Flowchart:
A flowchart is simply a graphical representation of steps. It shows steps in sequential order
and is widely used in presenting the flow of algorithms, workflow or process es. Typically, a
flowchart shows the steps as boxes of various kinds, and their order by connecting them with
arrows.

Flowchart Symbols

Flowline
1. Flowline Symbol: Shows the process’ direction. Each flowline connects tw blocks.
o

Terminal Symbol

2. Terminal Symbol: Indicates the beginning or end of a flowchart.

Process
3. Process: Represent a step in a process. This is the most common component of a flowchart.

Decision Symbol
4. Decision Symbol: Shows a step that decides the next step in a process. This is commonly a
yes/no or true/false question.

Input / Output

5. Input / Output Symbol: Indicates the process of inputting or outputting external data. This
is indicated by the shape of a parallelogram.

Annotation / Comment

6. Annotation / Comment Symbol: Indicates additional information regarding a step in a


process.

Predefined Process

7. Predefined Process Symbol: Shows named process which is defined elsewhere.

On-page Connector
8. On-page Connector Symbol are pairs of on-page connecter are used to replace long lines on
a flowchart page.

Off-page Connector

9. Off-page Connector Symbol: An off-page connector is used when the target is on another
page. Read our flowchart connector guide for more information on how on-p ge and off-page
a
connectors work.

Delay

10. Delay Symbol: Any delay period that is part of a process

Alternate Process

11. Alternate Process Symbol: An alternate to the normal process step. Flow lines to an
alternate process block is usually dashed.

Data

12. Data Symbol: Data input or output


Document

13. Document Symbol: A doc ument

Multi-document

14. Multi-document Symbol: Multiple documents

Preparation

15. Preparation Symbol: A preparation step

Display

16. Display Symbol: A machine display

Manual Input

17. Manual Input Symbol: Data or information into a system


Manual Operation

Example: Add two Numbers

The C program follows many steps in execution. To understand the flow of C program well, let us see
a simple program first.

File: simple.c

1. #include <stdio.h>
2. int main(){
3. printf("Hello C Language");
4. return 0;
5. }
Execution Flow

flow of above program by the figure given below.


1) C program (source code) is sent to preprocessor first. The preprocessor is responsible to convert
preprocessor directives into their respective values. The preprocessor generates an expanded source
code.

2) Expanded source code is sent to compiler which compiles the code and converts it into assembly
code.

3) The assembly code is sent to assembler which assembles the code and converts it into object code.
Now a simple.obj file is generated.

4) The object code is sent to linker which links it to the library such as header files. Then it is
converted into executable code. A simple.exe file is generated.

5) The executable code is sent to loader which loads it into memory and then it is executed. After
execution, output is sent to console.

C - Preprocessors

The C Preprocessor is not a part of the compiler, but is a separate step in the compilation
process. In simple terms, a C Preprocessor is just a text substitution tool and it instructs the compiler
to do required pre-processing before the actual compilation. We'll refer to the C Preprocessor as CPP.

All preprocessor commands begin with a hash symbol (#). It must be the first nonblank
character, and for readability, a preprocessor directive should begin in the first column. The following
section lists down all the important preprocessor directives −

Sr.No. Directive & Description

#define
1
Substitutes a preprocessor macro.

#include
2
Inserts a particular header from another file.

#undef
3
Undefines a preprocessor macro.

#ifdef
4
Returns true if this macro is defined.

#ifndef
5
Returns true if this macro is not defined.

#if
6
Tests if a compile time condition is true.

7 #else
The alternative for #if.

#elif
8
#else and #if in one statement.

#endif
9
Ends preprocessor conditional.

#error
10
Prints error message on stderr.

#pragma
11
Issues special commands to the compiler, using a standardized method.
Preprocessors Examples
#define MAX_ARRAY_LENGTH 20
This directive tells the CPP to replace instances of MAX_ARRAY_LENGTH with 20.
Use #define for constants to increase readability.

#include <stdio.h>
#include "myheader.h"
Tokens in C
Tokens in C is the most important element to be used in creating a program in C. We can define the
token as the smallest individual element in C. For `example, we cannot create a sentence without
using words; similarly, we cannot create a program in C without using tokens in C. Therefore, we can
say that tokens in C is the building block or the basic component for creating a program in C
language.

Classification of tokens in C

Tokens in C language can be divided into the following categories:

1. Keywords in C
2. Identifiers in C
3. Strings in C
4. Operators in C
5. Constant in C
6. Special Characters in C

Keywords in C

Keywords in C can be defined as the pre-defined or the reserved words having its own importance,
and each keyword has its own functionality. Since keywords are the pre-defined words used by the
compiler, so they cannot be used as the variable names. If the keywords are used as the variable
names, it means that we are assigning a different meaning to the keyword, which is not allowed. C
language supports 32 keywords 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
Identifiers in C

Identifiers in C are used for naming variables, functions, arrays, structures, etc. Identifiers in C are the
user-defined words. It can be composed of uppercase letters, lowercase letters, underscore, or digits,
but the starting letter should be either an underscore or an alphabet. Identifiers cannot be used as
keywords. Rules for constructing identifiers in C are given below:

o The first character of an identifier should be either an alphabet or an underscore, and then it
can be followed by any of the character, digit, or underscore.
o It should not begin with any numerical digit.
o In identifiers, both uppercase and lowercase letters are distinct. Therefore, we can say that
identifiers are case sensitive.
o Commas or blank spaces cannot be specified within an identifier.
o Keywords cannot be represented as an identifier.
o The length of the identifiers should not be more than 31 characters.
o Identifiers should be written in such a way that it is meaningful, short, and easy to read.

Strings in C

Strings in C are always represented as an array of characters having null character '\0' at the end of the
string. This null character denotes the end of the string. Strings in C are enclosed within double
quotes, while characters are enclosed within single characters. The size of a string is a number of
characters that the string contains.

Now, we describe the strings in different ways:

char a[10] = "javatpoint"; // The compiler allocates the 10 bytes to the 'a' array.

char a[] = "javatpoint"; // The compiler allocates the memory at the run time.

char a[10] = {'j','a','v','a','t','p','o','i','n','t','\0'}; // String is represented in the form of characters.

Operators in C
Operators in C is a special symbol used to perform the functions. The data items on which the
operators are applied are known as operands. Operators are applied between the operands. Depending
on the number of operands, operators are classified as follows:

Unary Operator

A unary operator is an operator applied to the single operand. For example: increment operator (++),
decrement operator (--), sizeof, (type)*.

Binary Operator

The binary operator is an operator applied between two operands. The following is the list of the
binary operators:

o Arithmetic Operators
o Relational Operators
o Shift Operators
o Logical Operators
o Bitwise Operators
o Conditional Operators
o Assignment Operator
o Misc Operator

Constants in C

A constant is a value assigned to the variable which will remain the same throughout the program,
i.e., the constant value cannot be changed.

There are two ways of declaring constant:

o Using const keyword


o Using #define pre-processor

Types of constants in C

Constant Example

Integer constant 10, 11, 34, etc.

Floating-point constant 45.6, 67.8, 11.2, etc.

Octal constant 011, 088, 022, etc.

Hexadecimal constant 0x1a, 0x4b, 0x6b, etc.

Character constant 'a', 'b', 'c', etc.


String constant "java", "c++", ".net", etc.
Special characters in C

Some special characters are used in C, and they have a special meaning which cannot be used for
another purpose.

o Square brackets [ ]: The opening and closing brackets represent the single and
multidimensional subscripts.
o Simple brackets ( ): It is used in function declaration and function calling. For example,
printf() is a pre-defined function.
o Curly braces { }: It is used in the opening and closing of the code. It is used in the opening
and closing of the loops.
o Comma (,): It is used for separating for more than one statement and for example, separating
function parameters in a function call, separating the variable when printing the value of more
than one variable using a single printf statement.
o Hash/pre-processor (#): It is used for pre-processor directive. It basically denotes that we are
using the header file.
o Asterisk (*): This symbol is used to represent pointers and also used as an operator for
multiplication.
o Tilde (~): It is used as a destructor to free memory.
o Period (.): It is used to access a member of a structure or a union.

Variables in C
A variable is a name of the memory location. It is used to store data. Its value can be changed, and it
can be reused many times.

It is a way to represent memory location through symbol so that it can be easily identified.

Let's see the syntax to declare a variable:

type variable_list;
The example of declaring the variable is given below:

int a;
float b;
char c;
Here, a, b, c are variables. The int, float, char are the data types.

We can also provide values while declaring the variables as given below:

int a=10, b=20; //declaring 2 variable of integer type


float f=20.8;
char c='A';
Rules for defining variables
o A variable can have alphabets, digits, and underscore.
o A variable name can start with the alphabet, and underscore only. It can't start with a digit.
o No whitespace is allowed within the variable name.
o A variable name must not be any reserved word or keyword, e.g. int, float, etc.

Valid variable names:

int a;
int _ab;
int a30;
Invalid variable names:

int 2;
int a b;
int long;
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.

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.

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


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

A data types in C refers to the type of data used to store information. For example, a

person's name would be an array of characters, whereas their age would be in integers.

On the other hand, a student's grades would necessitate using a data type that can

store decimal values.

There are four types of data types in C to differentiate and store various data types.

They are listed below:

 Basic data types in C


 Derived data types in C
 Enumeration data types in C
 Void data types in C

Basic Data Types in C

Basic data types in C are used to store values in integer and decimal formats. It can

handle both signed and unsigned literals. There are four basic or primitive data types in

C that can be signed or unsigned that are as follows:

• Int
• Float
• Double
• Char

Depending on the operating system, the memory size of these data types in C can vary
(32-bit or 64-bit). According to the 32-bit architecture, the table below shows the data
types commonly used in C programming, along with their storage size and value range.
Derived Data Types in C

The basic data types in C are used to store single values of various forms; however,

what if you need to store multiple values of the same data type? In this case, derived

data types enable you to combine basic data types and store multiple values in a single

variable.

The user defines the derived data types in C, and you can aggregate as many elements

of similar data types as you need. User-defined data type or derived data types are

classified into four types:

 Array
 Pointer
 Structure
 Union

Enumeration Data Types in C

Enumeration is a user-defined data type in C that are used to give names to integral

constants and improve program readability. The keyword for enumeration is 'enum,' and

its syntax is similar to the structure:

enum flag{const1, const2, const3……...};

Enumerations are preferable to '#define' for two reasons:

The compiler assigns default values to enum constants.

They are possible to declare in the local scope.

Void Data Type


The void data type in the C language is used to denote the lack of a particular type. Function return
types, function parameters, and pointers are three situations where it is frequently utilized.

Function Return Type:


A void return type function does not produce a value. A void function executes a task or action and
ends rather than returning a value.

Example:

1. void printHello() { printf("Hello, world!\n"); }


What is a C Operator?

Operators In C
An operator in C can be defined as the symbol that helps us to perform some specific mathematical,
relational, bitwise, conditional, or logical computations on values and variables. The values and
variables used with operators are called operands. So we can say that the operators are the symbols
that perform operations on operands.

For example,
c = a + b;
Here, ‘+’ is the operator known as the addition operator, and ‘a’ and ‘b’ are operands. The addition
operator tells the compiler to add both of the operands ‘a’ and ‘b’.
Types of Operators in C
C language provides a wide range of operators that can be classified into 6 types based on their
functionality:
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Other Operators

1. Arithmetic Operations in C
The arithmetic operators are used to perform arithmetic/mathematical operations on operands.
There are 9 arithmetic operators in C language:
S. No. Symbol Operator Description Syntax

1 + Plus Adds two numeric values. a+b


S. No. Symbol Operator Description Syntax

2 – Minus Subtracts right operand from left operand. a–b

3 * Multiply Multiply two numeric values. a*b

4 / Divide Divide two numeric values. a/b

Returns the remainder after diving the left operand


% Modulus a%b
5 with the right operand.

6 + Unary Plus Used to specify the positive values. +a

Unary
– Flips the sign of the value. -a
7 Minus

8 ++ Increment Increases the value of the operand by 1. a++

9 — Decrement Decreases the value of the operand by 1. a–

Example of C Arithmetic Operators


// C program to illustrate the arithmatic operators
#include <stdio.h>

int main()
{

int a = 25, b = 5;

// using operators and printing results


printf("a + b = %d\n", a + b);
printf("a - b = %d\n", a - b);
printf("a * b = %d\n", a * b);
printf("a / b = %d\n", a / b);
printf("a % b = %d\n", a % b);
printf("+a = %d\n", +a);
printf("-a = %d\n", -a);
printf("a++ = %d\n", a++);
printf("a-- = %d\n", a--);

return 0;
}
Output
a + b = 30
a - b = 20
a * b = 125
a/b=5
a%b=0
+a = 25
-a = -25
a++ = 25
a-- = 26

2. Relational Operators in C
The relational operators in C are used for the comparison of the two operands. All these operators
are binary operators that return true or false values as the result of comparison.
These are a total of 6 relational operators in C:
S.
No. Symbol Operator Description Syntax

Returns true if the left operand is less than the


< Less than a<b
1 right operand. Else false

Returns true if the left operand is greater than the


> Greater than a>b
2 right operand. Else false

Less than or Returns true if the left operand is less than or


<= a <= b
3 equal to equal to the right operand. Else false

Greater than or Returns true if the left operand is greater than or


>= a >= b
4 equal to equal to right operand. Else false

5 == Equal to Returns true if both the operands are equal. a == b

6 != Not equal to Returns true if both the operands are NOT equal. a != b

Example of C Relational Operators


// C program to illustrate the relational operators
#include <stdio.h>

int main()
{

int a = 25, b = 5;

// using operators and printing results


printf("a < b : %d\n", a < b);
printf("a > b : %d\n", a > b);
printf("a <= b: %d\n", a <= b);
printf("a >= b: %d\n", a >= b);
printf("a == b: %d\n", a == b);
printf("a != b : %d\n", a != b);

return 0;
}

Output
a<b :0
a>b :1
a <= b: 0
a >= b: 1
a == b: 0
a != b : 1
Here, 0 means false and 1 means true.

3. Logical Operator in C
Logical Operators are used to combine two or more conditions/constraints or to complement the
evaluation of the original condition in consideration. The result of the operation of a logical
operator is a Boolean value either true or false.
S. No. Symbol Operator Description Syntax

1 && Logical AND Returns true if both the operands are true. a && b

2 || Logical OR Returns true if both or any of the operand is true. a || b

3 ! Logical NOT Returns true if the operand is false. !a

Example of Logical Operators in C

// C program to illustrate the logical operators


#include <stdio.h>

int main()
{

int a = 25, b = 5;

// using operators and printing results


printf("a && b : %d\n", a && b);
printf("a || b : %d\n", a || b);
printf("!a: %d\n", !a);

return 0;
}

Output
a && b : 1
a || b : 1
!a: 0

4. Bitwise Operators in C
The Bitwise operators are used to perform bit-level operations on the operands. The operators are
first converted to bit-level and then the calculation is performed on the operands. Mathematical
operations such as addition, subtraction, multiplication, etc. can be performed at the bit level for
faster processing.
There are 6 bitwise operators in C:
S.
No. Symbol Operator Description Syntax

Performs bit-by-bit AND operation and returns a &&


& Bitwise AND
1 the result. b

Performs bit-by-bit OR operation and returns


| Bitwise OR a || b
2 the result.

Performs bit-by-bit XOR operation and returns


^ Bitwise XOR a^b
3 the result.

Bitwise First
~ Flips all the set and unset bits on the number. ~a
4 Complement

Shifts the number in binary form by one place


<< Bitwise Leftshift a << b
5 in the operation and returns the result.
S.
No. Symbol Operator Description Syntax

Shifts the number in binary form by one place


>> Bitwise Rightshilft a >> b
6 in the operation and returns the result.

Example of Bitwise Operators

// C program to illustrate the bitwise operators


#include <stdio.h>

int main()
{

int a = 25, b = 5;

// using operators and printing results


printf("a & b: %d\n", a & b);
printf("a | b: %d\n", a | b);
printf("a ^ b: %d\n", a ^ b);
printf("~a: %d\n", ~a);
printf("a >> b: %d\n", a >> b);
printf("a << b: %d\n", a << b);

return 0;
}

Output
a & b: 1
a | b: 29
a ^ b: 28
~a: -26
a >> b: 0
a << b: 800
5. Assignment Operators in C
Assignment operators are used to assign value to a variable. The left side operand of the assignment
operator is a variable and the right side operand of the assignment operator is a value. The value on
the right side must be of the same data type as the variable on the left side otherwise the compiler
will raise an error.
The assignment operators can be combined with some other operators in C to provide multiple
operations using single operator. These operators are called compound operators.
In C, there are 11 assignment operators:
S.
No. Symbol Operator Description Syntax

Simple Assign the value of the right operand to the left


= a=b
1 Assignment operand.

Add the right operand and left operand and assign


+= Plus and assign a += b
2 this value to the left operand.

Minus and Subtract the right operand and left operand and
-= a -= b
3 assign assign this value to the left operand.

Multiply and Multiply the right operand and left operand and
*= a *= b
4 assign assign this value to the left operand.

Divide and Divide the left operand with the right operand and
/= a /= b
5 assign assign this value to the left operand.

Modulus and Assign the remainder in the division of left a %=


%=
6 assign operand with the right operand to the left operand. b

Performs bitwise AND and assigns this value to


&= AND and assign a &= b
7 the left operand.

Performs bitwise OR and assigns this value to the


|= OR and assign a |= b
8 left operand.

XOR and Performs bitwise XOR and assigns this value to


^= a ^= b
9 assign the left operand.

Rightshift and Performs bitwise Rightshift and assign this value a >>=
>>=
10 assign to the left operand. b

Leftshift and Performs bitwise Leftshift and assign this value to a <<=
<<=
11 assign the left operand. b

Example of C Assignment Operators

// C program to illustrate the arithmatic operators


#include <stdio.h>

int main()
{

int a = 25, b = 5;

// using operators and printing results


printf("a = b: %d\n", a = b);
printf("a += b: %d\n", a += b);
printf("a -= b: %d\n", a -= b);
printf("a *= b: %d\n", a *= b);
printf("a /= b: %d\n", a /= b);
printf("a %= b: %d\n", a %= b);
printf("a &= b: %d\n", a &= b);
printf("a |= b: %d\n)", a |= b);
printf("a >>= b: %d\n", a >> b);
printf("a <<= b: %d\n", a << b);

return 0;
}
Output
a = b: 5
a += b: 10
a -= b: 5
a *= b: 25
a /= b: 5
a %= b: 0
a &= b: 0
a |= b: 5
)a >>= b: 0
a <<= b: 160

6. Other Operators
Apart from the above operators, there are some other operators available in C used to perform some
specific tasks. Some of them are discussed here:
sizeof Operator
 sizeof is much used in the C programming language.
 It is a compile-time unary operator which can be used to compute the size of its operand.
 The result of sizeof is of the unsigned integral type which is usually denoted by size_t.
 Basically, the sizeof the operator is used to compute the size of the variable or datatype.
Syntax
sizeof (operand)
To know more about the topic refer to this article.
Comma Operator ( , )
 The comma operator (represented by the token) is a binary operator that evaluates its first
operand and discards the result, it then evaluates the second operand and returns this value (and
type).
 The comma operator has the lowest precedence of any C operator.
 Comma acts as both operator and separator.
Syntax
operand1 , operand2
To know more about the topic refer to this article.
Conditional Operator ( ? : )
 The conditional operator is the only ternary operator in C++.
 Here, Expression1 is the condition to be evaluated. If the condition(Expression1) is True then
we will execute and return the result of Expression2 otherwise if the condition(Expression1)
is false then we will execute and return the result of Expression3.
 We may replace the use of if..else statements with conditional operators.
Syntax
operand1 ? operand2 : operand3;
To know more about the topic refer to this article.
dot (.) and arrow (->) Operators
 Member operators are used to reference individual members of classes, structures, and unions.
 The dot operator is applied to the actual object.
 The arrow operator is used with a pointer to an object.
Syntax
structure_variable . member;
and
structure_pointer -> member;
To know more about dot operators refer to this article and to know more about arrow(->) operators
refer to this article.
Cast Operator
 Casting operators convert one data type to another. For example, int(2.2000) would return 2.
 A cast is a special operator that forces one data type to be converted into another.
 The most general cast supported by most of the C compilers is as follows − [ (type)
expression ].
Syntax
(new_type) operand;
To know more about the topic refer to this article.
addressof (&) and Dereference (*) Operators
 Pointer operator & returns the address of a variable. For example &a; will give the actual
address of the variable.
 The pointer operator * is a pointer to a variable. For example *var; will pointer to a variable
var.
To know more about the topic refer to this article.
Example of Other C Operators

// C Program to demonstrate the use of Misc operators


#include <stdio.h>

int main()
{
// integer variable
int num = 10;
int* add_of_num = #

printf("sizeof(num) = %d bytes\n", sizeof(num));


printf("&num = %p\n", &num);
printf("*add_of_num = %d\n", *add_of_num);
printf("(10 < 5) ? 10 : 20 = %d\n", (10 < 5) ? 10 : 20);
printf("(float)num = %f\n", (float)num);

return 0;
}
Output
sizeof(num) = 4 bytes
&num = 0x7ffe2b7bdf8c
*add_of_num = 10
(10 < 5) ? 10 : 20 = 20
(float)num = 10.000000

You might also like