Units Cost Accounting Pankaj and The Reserve Bank of India
Units Cost Accounting Pankaj and The Reserve Bank of India
Introduction to C
C programming is considered as the base for other programming languages, that is why it is
known as mother language.
1. Mother 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.
It can't be used for internet programming like Java, .Net, PHP, etc.
3) C as a procedural language
A procedural language breaks the program into functions, data structures, etc.
In the C language, we break the program into parts using functions. It makes the program easier
to understand and modify.
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.
Unlike assembly language, c programs can be executed on different machines with some
machine specific changes. Therefore, C is a machine independent 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
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
History of C:
C Programming history:-
Any C program is consists of 6 main sections. Below you will find brief explanation of each of
them.
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';
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 −
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
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
Predefined Process
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
Alternate Process
11. Alternate Process Symbol: An alternate to the normal process step. Flow lines to an
alternate process block is usually dashed.
Data
Multi-document
Preparation
Display
Manual Input
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
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 −
#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
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
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.
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.
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.
Types of constants in C
Constant Example
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.
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;
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.
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.
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.
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
There are four types of data types in C to differentiate and store various data types.
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
• 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
Array
Pointer
Structure
Union
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
Example:
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
Unary
– Flips the sign of the value. -a
7 Minus
int main()
{
int a = 25, b = 5;
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
6 != Not equal to Returns true if both the operands are NOT equal. a != b
int main()
{
int a = 25, b = 5;
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
int main()
{
int a = 25, b = 5;
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
Bitwise First
~ Flips all the set and unset bits on the number. ~a
4 Complement
int main()
{
int a = 25, b = 5;
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
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.
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
int main()
{
int a = 25, b = 5;
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
int main()
{
// integer variable
int num = 10;
int* add_of_num = #
return 0;
}
Output
sizeof(num) = 4 bytes
&num = 0x7ffe2b7bdf8c
*add_of_num = 10
(10 < 5) ? 10 : 20 = 20
(float)num = 10.000000