C Notes From Nepal
C Notes From Nepal
C Notes From Nepal
Chapter: 1
Principles of Programming
1.1 Illustrate the terms Program, Programmer,
Programming Language and Software
• Program:
A computer program is a sequence of instructions written using a Computer
Programming Language to perform a specified task by the computer.
The two important terms that we have used in the above definition are −
1. Sequence of instructions
2. Computer Programming Language
• Programmer:
Someone who can write computer programs or in other words, someone who can do
computer programming is called a Computer Programmer.
- C Programmer
- C++ Programmer
- Java Programmer
• Programming Language
A program is a set of instructions that help computer to perform tasks. This set of
instructions is also called as scripts. Programs are executed by processor whereas scripts
are interpreted. The languages that are used to write a program or set of instructions
are called "Programming languages". Programming languages are broadly categorized
into three types-
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
2
• Software
Software is a set of programs, which is designed to perform a well-defined function. A
program is a sequence of instructions written to solve a particular problem.
- System Software
- Application Software
- Utilities Program
The computer system is simply a machine and hence it cannot perform any work; therefore,
in order to make it functional different languages are developed, which are known as
programming languages or simply computer languages.
Following are the major categories of Programming Languages −
1. Machine Language
2. Assembly Language
3. High Level Language
4. System Language
5. Scripting Language
But obviously, the computer can follow any one of the logics at a time, not both the logics
simultaneously. To make the computer understand, a program can be written using only 0s
and 1s. The data can also be specified and represented using only 0s and 1s. Such a program
is called Machine Language program.
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
3
High-level languages are like English-like language, with less words also known as keywords
and fewer ambiguities. Each high-level language will have its own syntax and keywords. The
meaning of the word syntax is grammar.
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
4
• Scientific Application:
Programming has played vital role in Scientific Development and research; different
scientific equipment’s are programmed to show digital values. Calculations needed for
the scientific research are done by the computer which are programmed. Custom
Software are developed to meet the specific demands of the scientist. Scientist use
programming to develop and deploy different machines and robots that are
automatically operated.
• Business Application:
Business used programming languages to make custom payroll, accounting, inventory
management system to store data of the used and daily usage. Now a days all the billing
and inventory management is done by using programming language which is more
acceptable and reliable than humans.
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
5
a. Algorithm
b. Flowchart
c. Pseudocode
a. Algorithm
An algorithm is a set of steps of operations to solve a problem performing
calculation, data processing, and automated reasoning tasks. An algorithm is an
efficient method that can be expressed within finite amount of time and space.
An algorithm is the best way to represent the solution of a particular problem in a
very simple and efficient way. If we have an algorithm for a specific problem, then
we can implement it in any programming language, meaning that the algorithm is
independent from any programming languages.
The main characteristics of algorithms are as follows −
o Algorithms must have a unique name
o Algorithms should have explicitly defined set of inputs and outputs
o Algorithms are well-ordered with unambiguous operations
o Algorithms halt in a finite amount of time. Algorithms should not run for infinity,
i.e., an algorithm must end at some point
Step 1: Start
Step 2: Input Two Numbers X And Y
Step 3: Read Two Numbers X And Y
Step 4: Z=X+Y
Step 5: Display Result Z
Step 6: Stop
b. Flowchart
A flowchart is simply a graphical representation of steps. It shows steps in a
sequential order, and is widely used in presenting flow of algorithms, workflow or
processes. Typically, flowchart shows the steps as boxes of various kinds, and them
order by connecting them with arrows. Below are the shapes used in Flowchart:
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
6
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
7
c. Pseudocode
Pseudocode gives a high-level description of an algorithm without the ambiguity
associated with plain text but also without the need to know the syntax of a particular
programming language.
The running time can be estimated in a more general manner by using Pseudocode
to represent the algorithm as a set of fundamental operations which can then be
counted.
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
8
Chapter: 2
Fundamentals of C
2.1 Introduce C Programming, Features of C Programming
and Applications of C Programming
In 1978, Brian Kernighan and Dennis Ritchie produced the first publicly available description
of C, now known as the K&R standard. The UNIX operating system, the C compiler, and
essentially all UNIX application programs have been written in C.
C has now become a widely used professional language for various reasons:
- Easy to learn
- Structured language
- It produces efficient programs
- It can handle low-level activities
- It can be compiled on a variety of computer platforms
Characteristics/Features
Some of C's characteristics that define the language and also have led to its popularity’s
programming language. This course has included these aspects:
Portability
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
9
One of the reasons of C’s popularity is its portability. We can easily transform a program
written in C from one computer to another with few or no changes and compile with
appropriate compilers.
Extendibility
Another property is extendibility. C is basically a collection of functions that are supported
by library. We can continuously add our own functions to C library.
Flexible
C is a flexible language. It permits us to write any complex programs with the help of its rich
set of in-built functions and operators. In addition, it permits the use of low-level language.
Hence it is also called “middle-level language” and therefore it is well suited for both system
software and business package.
Applications Of C Programming
C was initially used for system development work, particularly the programs thatmake-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 might be:
- Operating Systems
- Language Compilers
- Assemblers
- Text Editors
- Print Spoolers
- Network Drivers
- Modern Programs
- Databases
- Language Interpreters
- Utilities
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
10
- Documentation Section
- Preprocessor Directive Section
- Global Declaration Section
- Main Program Section
- Sub Program Section
The first and the second line of the program #include <stdio.h> and #include <conio.h> is a
preprocessor command, which tells a C compiler to include stdio.h file before going to actual
compilation.
The third line give the deceleration of a function called fun() which is void.
The fourth line is Global Variable declaration section, int a = 10; is accessible through the
program.
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
11
The next line void main() is the main function where the program execution begins. The first
line Of this function clears the screen using the function clrscr(). The second line prints the
value of a that is 10 and the last line calls the functions fun().
The last section is subprogram section, where we declare User defined functions.
Syntax in C
The syntax of the C programming language is the set of rules governing writing of software
in the C language.
Having a syntax error doesn't mean your code's logic is incorrect, it means you have written
it incorrectly. Once the syntax is correct, then only the code is compiled and then run.
Example
#include <stdio.h>
int main() {
printf("Hello World!");
return 0;
Preprocessor Directive
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 –
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
12
#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.
Header Files
In C language, header files contain the set of predefined standard library functions. The
“#include” preprocessing directive is used to include the header files with “.h” extension in
the program.
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
13
Here is the table that displays some of the header files in C language,
Tokens in C
A C program consists of various tokens and a token is either a keyword, an identifier, a
constant, a string literal, or a symbol. For example, the following C statement consists of five
tokens:
printf
Semicolons
In a C program, the semicolon is a statement terminator. That is, each individual statement
must be ended with a semicolon. It indicates the end of one logical entity.
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
14
return 0;
Comments
Comments are like helping text in your C program and they are ignored by the compiler.
They start with /* and terminate with the characters */ as shown below:
/* This is
Multi-line
comment*/
We can also give a single line comment using the character //.
Identifiers
A C identifier is a name used to identify a variable, function, or any other userdefined item.
An identifier starts with a letter A to Z, a to z, or an underscore ‘_’ followed by zero or more
letters, underscores, and digits (0 to 9).
C does not allow punctuation characters such as @, $, and % within identifiers. C is a case-
sensitive programming language. Thus, Manpower and manpower are two different
identifiers in C. Here are some examples of acceptable identifiers:
Whitespace in C
A line containing only whitespace, possibly with a comment, is known as a blank line, and a C
compiler totally ignores it.
Whitespace is the term used in C to describe blanks, tabs, newline characters and
comments. Whitespace separates one part of a statement from another and enables the
compiler to identify where one element in a statement, such as int, ends and the next
element begins. Therefore, in the following statement:
int age;
there must be at least one whitespace character (usually a space) between int and age for
the compiler to be able to distinguish them. On the other hand, in the following statement:
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
15
no whitespace characters are necessary between fruit and =, or between = and apples,
although you are free to include some if you wish to increase readability.
Escape Sequences
Many programming languages support a concept called Escape Sequence. When a character
is preceded by a backslash (\), it is called an escape sequence and it has a special meaning to
the compiler. For example, \n in the following statement is a valid character and it is called a
new line character −
char ch = '\n';
The following table lists the escape sequences available in C programming language −
A variable is nothing but a name given to a storage area that our programs can manipulate.
The name of a variable can be composed of letters, digits, and the underscore character. It
must begin with either a letter or an underscore. Upper and lowercase letters are distinct
because C is case-sensitive. Based on the basic types explained in the previous chapter,
there will be the following basic variable types –
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
16
A variable definition specifies a data type and contains a list of one or more variables of that
type as follows −
type variable_list;
int i;
int j =10;
char c, ch;
float f, salary;
double d;
Keywords
The following list shows the reserved words in C. These reserved words may not be used as
constants or variables or any other identifier names.
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
17
Digits – 0…9
Constant
Constants are fixed values that cannot be altered by the program and can be
Some Examples: -
unsigned: 0, 255
Variable
A variable is a named piece of memory which is used to hold a value which may be modified
by the program. A variable thus has three attributes that are of interest to us: its type, its
value and its address.
The variable’s type informs us what type and range of values it can represent and how much
memory is used to store that value. The variable’s address informs us where in memory the
variable is located (which will become increasingly important when we discuss pointers later
on).
datatype variable-list;
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
18
For Example: -
int i;
char a, b, ch;
- Primary Datatype
- Derived Datatype
Primary/Fundamental Datatype
The data type that is used without any modifier is known as primary data type. The primary
data type can be categorized as follows:
1. Integer Type
a. Signed Integer Type
⚫ int
⚫ shortint
⚫ longint
b. unsigned integer type
⚫ unsigned int
⚫ unsigned shortint
⚫ unsigned longint
2. Character Type
a. signedchar
b. unsignedchar
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
19
• int - integer: a whole number. We can think of it as a positive or negative whole number.
But no fractional part is allowed. To declare an int you use the instruction:
int a;
To declare a variable of type character we use the keyword char. - A single character stored in
one byte.
For example:
char c;
To assign, or store, a character value in a char data type is easy - a character variable is just a
symbol enclosed by single quotes. For example, if c is a char variable you can store the letter A
in it using the following C statement:
c='A'
Notice that you can only store a single character in a char variable. But a string constant is
written between double quotes. Remember that a char variable is 'A' and not "A".
Here is the list of data types with their corresponding required memory range of value it can
take:
MEMORY FORMAT
DATA TYPE (BYTES) RANGE SPECIFIER
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
20
Format Specifiers in C
The symbols that are used to represent the type/format of the value being read and
processed is known as format specifier.
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
21
When we say Output, it means to display some data on screen, printer, or in any file. C
programming provides a set of built-in functions to output the data on the computer screen
as well as to save it in text or binary files.
The file pointers are the means to access the file for reading and writing purpose. This
section explains how to read values from the screen and how to print the result on the
screen.
The int putchar(int c) function puts the passed character on the screen and returns the same
character. This function puts only single character at a time. You can use this method in the
loop in case you want to display more than one character on the screen. Check the following
example:
#include <stdio.h>
int main( ) {
int c;
c = getchar( );
putchar( c );
return 0;
When the above code is compiled and executed, it waits for you to input some text. When
you enter a text and press enter, then the program proceeds and reads only a single
character and displays it as follows −
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
22
You entered: t
The int puts(const char *s) function writes the string 's' and 'a' trailing newline to stdout.
NOTE: Though it has been deprecated to use gets() function, Instead of using gets, you want
to use fgets().
#include <stdio.h>
int main( ) {
char str[100];
gets( str );
puts( str );
return 0;
When the above code is compiled and executed, it waits for you to input some text. When
you enter a text and press enter, then the program proceeds and reads the complete line till
end, and displays it as follows –
The int printf(const char *format, ...) function writes the output to the standard output
stream stdout and produces the output according to the format provided.
The format can be a simple constant string, but you can specify %s, %d, %c, %f, etc., to print
or read strings, integer, character or float respectively. There are many other formatting
options available which can be used based on requirements. Let us now proceed with a
simple example to understand the concepts better −
#include <stdio.h>
int main( ) {
char str[100];
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
23
int i;
return 0;
When the above code is compiled and executed, it waits for you to input some text. When
you enter a text and press enter, then program proceeds and reads the input and displays it
as follows −
Here, it should be noted that scanf() expects input in the same format as you provided %s
and %d, which means you have to provide valid inputs like "string integer". If you provide
"string string" or "integer integer", then it will be assumed as wrong input. Secondly, while
reading a string, scanf() stops reading as soon as it encounters a space, so "this is test" are
three strings for scanf().
An operator is a symbol that tells the compiler to perform specific mathematical or logical
functions. C language is rich in built-in operators and provides the following types of
operators:
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
Arithmetic Operators
The following table shows all the arithmetic operators supported by the C language. Assume
variable A holds 10 and variable B holds 20 then −
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
24
Example:
#include <stdio.h>
main()
{
int a = 21;
int b = 10;
int c ;
c = a + b;
printf("Line 1 - Value of c is %d\n", c );
c = a - b;
printf("Line 2 - Value of c is %d\n", c );
c = a * b;
printf("Line 3 - Value of c is %d\n", c );
c = a / b;
printf("Line 4 - Value of c is %d\n", c );
c = a % b;
printf("Line 5 - Value of c is %d\n", c );
c = a++;
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
25
c = a--;
printf("Line 7 - Value of c is %d\n", c );
}
Relational Operators
The following table shows all the relational operators supported by C. Assume
variable A holds 10 and variable B holds 20 then −
== Checks if the values of two operands are equal or not. If (A == B) is not true.
yes, then the condition becomes true.
!= Checks if the values of two operands are equal or not. If the (A != B) is true.
values are not equal, then the condition becomes true.
> Checks if the value of left operand is greater than the value (A > B) is not true.
of right operand. If yes, then the condition becomes true.
< Checks if the value of left operand is less than the value of (A < B) is true.
right operand. If yes, then the condition becomes true.
>= Checks if the value of left operand is greater than or equal (A >= B) is not true.
to the value of right operand. If yes, then the condition
becomes true.
<= Checks if the value of left operand is less than or equal to (A <= B) is true.
the value of right operand. If yes, then the condition
becomes true.
Example
#include <stdio.h>
main() {
int a = 21;
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
26
int b = 10;
int c ;
if( a == b ) {
printf("Line 1 - a is equal to b\n" );
} else {
printf("Line 1 - a is not equal to b\n" );
}
if ( a < b ) {
printf("Line 2 - a is less than b\n" );
} else {
printf("Line 2 - a is not less than b\n" );
}
if ( a > b ) {
printf("Line 3 - a is greater than b\n" );
} else {
printf("Line 3 - a is not greater than b\n" );
}
if ( a <= b ) {
printf("Line 4 - a is either less than or equal to b\n" );
}
if ( b >= a ) {
printf("Line 5 - b is either greater than or equal to b\n" );
}
}
Logical Operators
Following table shows all the logical operators supported by C language. Assume
variable A holds 1 and variable B holds 0, then −
&& Called Logical AND operator. If both the operands are non-zero, (A && B) is false.
then the condition becomes true.
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
27
! Called Logical NOT Operator. It is used to reverse the logical !(A && B) is true.
state of its operand. If a condition is true, then Logical NOT
operator will make it false.
Example
#include <stdio.h>
main()
{
int a = 5;
int b = 20;
int c;
if (a && b)
{
printf("Line 1 - Condition is true\n");
}
if (a || b)
{
printf("Line 2 - Condition is true\n");
}
if (a && b)
{
printf("Line 3 - Condition is true\n");
}
else
{
printf("Line 3 - Condition is not true\n");
}
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
28
Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation.
& Binary AND Operator copies a bit to the result if it exists in both (A & B) = 12, i.e.,
operands. 0000 1100
^ Binary XOR Operator copies the bit if it is set in one operand but (A ^ B) = 49, i.e.,
not both. 0011 0001
<< Binary Left Shift Operator. The left operands value is moved left
by the number of bits specified by the right operand. A << 2 = 240 i.e.,
1111 0000
>> Binary Right Shift Operator. The left operands value is moved
right by the number of bits specified by the right operand. A >> 2 = 15 i.e.,
0000 1111
Example
#include <stdio.h>
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
29
main()
{
c = a | b; /* 61 = 0011 1101 */
printf("Line 2 - Value of c is %d\n", c);
c = a ^ b; /* 49 = 0011 0001 */
printf("Line 3 - Value of c is %d\n", c);
Assignment Operators
The following table lists the assignment operators supported by the C language −
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
30
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
31
Example
#include <stdio.h>
main()
{
int a = 21;
int c;
c = a;
printf("Line 1 - = Operator Example, Value of c = %d\n", c);
c += a;
printf("Line 2 - += Operator Example, Value of c = %d\n", c);
c -= a;
printf("Line 3 - -= Operator Example, Value of c = %d\n", c);
c *= a;
printf("Line 4 - *= Operator Example, Value of c = %d\n", c);
c /= a;
printf("Line 5 - /= Operator Example, Value of c = %d\n", c);
c = 200;
c %= a;
printf("Line 6 - %= Operator Example, Value of c = %d\n", c);
c <<= 2;
printf("Line 7 - <<= Operator Example, Value of c = %d\n", c);
c >>= 2;
printf("Line 8 - >>= Operator Example, Value of c = %d\n", c);
c &= 2;
printf("Line 9 - &= Operator Example, Value of c = %d\n", c);
c ^= 2;
printf("Line 10 - ^= Operator Example, Value of c = %d\n", c);
c |= 2;
printf("Line 11 - |= Operator Example, Value of c = %d\n", c);
}
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
32
Chapter: 3
Control Flow Statements
Decision making structures require that the programmer specifies one or more conditions to
be evaluated or tested by the program, along with a statement or statements to be
executed if the condition is determined to be true, and optionally, other statements to be
executed if the condition is determined to be false.
Show below is the general form of a typical decision-making structure found in most of the
programming languages −
C programming language assumes any non-zero and non-null values as true, and if it is either
zero or null, then it is assumed as false value.
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
33
if statement
if...else statement
nested if statements
switch statement
If Statement:
An if statement consists of a Boolean expression followed by one or more statements.
Syntax:
The syntax of an 'if' statement in C programming language is −
If (boolean_expression) {
/* statement(s) */
}
If the Boolean expression evaluates to true, then the block of code inside the 'if' statement
will be executed. If the Boolean expression evaluates to false, then the first set of code after
the end of the 'if' statement (after the closing curly brace) will be executed.
C programming language assumes any non-zero and non-null values as true and if it is either
zero or null, then it is assumed as false value.
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
34
Flow Diagram:
Example:
#include <stdio.h>
int main () {
int a = 10;
if( a < 20 ) {
printf("a is less than 20\n" );
}
printf("value of a is: %d\n", a);
return 0;
}
Output:
a is less than 20;
value of a is: 10
If else Statement:
An if statement can be followed by an optional else statement, which executes when the
Boolean expression is false.
Syntax:
if(boolean_expression) {
/* statement(s) */
} else {
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
35
/* statement(s) */
If the Boolean expression evaluates to true, then the if block will be executed, otherwise, the
else block will be executed.
C programming language assumes any non-zero and non-null values as true, and if it is either
zero or null, then it is assumed as false value.
Flow Diagram:
Example:
#include <stdio.h>
int main () {
int a = 100;
if( a < 20 ) {
} else {
return 0;
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
36
Output:
a is not less than 20;
When using if...else if..else statements, there are few points to keep in mind −
• An if can have zero or one else's and it must come after any else if's.
• An if can have zero to many else if's and they must come before the else.
• Once an else if succeeds, none of the remaining else if's or else's will be tested.
Syntax:
if(boolean_expression 1) {
} else {
Example:
#include <stdio.h>
int main () {
int a = 100;
if( a == 10 ) {
printf("Value of a is 10\n" );
} else if( a == 20 ) {
printf("Value of a is 20\n" );
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
37
} else if( a == 30 ) {
printf("Value of a is 30\n" );
} else {
return 0;
Output:
None of the values is matching
Switch Statement
A switch statement allows a variable to be tested for equality against a list of values. Each
value is called a case, and the variable being switched on is checked for each switch case.
Syntax:
switch(expression) {
case constant-expression 1:
statement(s);
break;
case constant-expression 2:
statement(s);
break;
statement(s);
break;
default:
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
38
statement(s);
Flow Diagram:
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
39
Example:
#include <stdio.h>
int main () {
switch(grade) {
case 'A' :
printf("Excellent!\n" );
break;
case 'B' :
case 'C' :
printf("Well done\n" );
break;
case 'D' :
printf("You passed\n" );
break;
case 'F' :
break;
default :
printf("Invalid grade\n" );
return 0;
Output:
Well done
Your grade is B
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
40
Programming languages provide various control structures that allow for more complicated
execution paths.
for loop
2 Executes a sequence of statements multiple times and abbreviates
the code that manages the loop variable.
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
41
do...while loop
nested loops
4 You can use one or more loops inside any other while, for, or do while
loop.
Syntax:
while(condition) {
statement(s);
Here, statement(s) may be a single statement or a block of statements. The condition may
be any expression, and true is any nonzero value. The loop iterates while the condition is
true.
When the condition becomes false, the program control passes to the line immediately
following the loop.
Flow Diagram:
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
42
Here, the key point to note is that a while loop might not execute at all. When the condition
is tested and the result is false, the loop body will be skipped and the first statement after
the while loop will be executed.
Example:
#include <stdio.h>
int main () {
int a = 10;
while( a < 20 ) {
a++;
return 0;
Output:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
For Loop
A for loop is a repetition control structure that allows you to efficiently write a loop that
needs to execute a specific number of times.
Syntax:
for ( init; condition; increment ) {
//statement(s);
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
43
• The init step is executed first, and only once. This step allows you to declare and
initialize any loop control variables. You are not required to put a statement here, as
long as a semicolon appears.
• Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is
false, the body of the loop does not execute and the flow of control jumps to the
next statement just after the 'for' loop.
• After the body of the 'for' loop executes, the flow of control jumps back up to the
increment statement. This statement allows you to update any loop control
variables. This statement can be left blank, as long as a semicolon appears after the
condition.
• The condition is now evaluated again. If it is true, the loop executes and the process
repeats itself (body of loop, then increment step, and then again condition). After
the condition becomes false, the 'for' loop terminates.
Flow Diagram:
Example:
#include <stdio.h>
int main () {
int a;
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
44
return 0;
Output:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Do while Loop
Unlike for and while loops, which test the loop condition at the top of the loop, the
do...while loop in C programming checks its condition at the bottom of the loop.
A do...while loop is similar to a while loop, except the fact that it is guaranteed to execute at
least one time.
Syntax:
do {
statement(s);
} while( condition );
Notice that the conditional expression appears at the end of the loop, so the statement(s) in
the loop executes once before the condition is tested.
If the condition is true, the flow of control jumps back up to do, and the statement(s) in the
loop executes again. This process repeats until the given condition becomes false.
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
45
Flow Diagram:
Example:
#include <stdio.h>
int main () {
int a = 10;
do {
a = a + 1;
} while( a < 20 );
return 0;
Output:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
46
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Nested Loop
C programming allows to use one loop inside another loop. The following section shows a
few examples to illustrate the concept.
Syntax:
for ( init; condition; increment ) {
statement(s);
statement(s);
The syntax for a nested while loop statement in C programming language is as follows –
while(condition) {
while(condition) {
statement(s);
statement(s);
The syntax for a nested do...while loop statement in C programming language is as follows −
do {
statement(s);
do {
statement(s);
} while (condition);
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
47
} while (condition);
A final note on loop nesting is that you can put any type of loop inside any other type of
loop. For example, a 'for' loop can be inside a 'while' loop or vice versa.
Example:
The following program uses a nested for loop to find the prime numbers from 2 to 100 −
#include <stdio.h>
int main () {
int i, j;
return 0;
Output:
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
48
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
49
When a break statement is encountered inside a loop, the loop is immediately terminated
and the program control resumes at the next statement following the loop.
It can be used to terminate a case in the switch statement (covered in the next chapter).
If you are using nested loops, the break statement will stop the execution of the innermost
loop and start executing the next line of code after the block.
Syntax:
break;
Flow Diagram:
Example:
#include <stdio.h>
int main () {
int a = 10;
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
50
while( a < 20 ) {
a++;
break;
return 0;
Output:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
Continue Statement:
The continue statement in C programming works somewhat like the break statement.
Instead of forcing termination, it forces the next iteration of the loop to take place, skipping
any code in between.
For the for loop, continue statement causes the conditional test and increment portions of
the loop to execute. For the while and do...while loops, continue statement causes the
program control to pass to the conditional tests.
Syntax:
continue;
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
51
Flow Diagram:
Example:
#include <stdio.h>
int main () {
int a = 10;
do {
if( a == 15) {
a = a + 1;
continue;
a++;
} while( a < 20 );
return 0;
Output:
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
52
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Return Statement:
The return statement returns the flow of the execution to the function from where it is
called. This statement does not mandatorily need any conditional statements. As soon as the
statement is executed, the flow of the program stops immediately and returns the control
from where it was called. The return statement may or may not return anything for a void
function, but for a non-void function, a return value must be returned.
Syntax:
return[expression];
Example:
#include <stdio.h>
void Print()
printf("Welcome to GeeksforGeeks");
int main()
Print();
return 0;
Output:
Welcome to GeeksforGeeks
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
53
Chapter: 4
Function
Concept of Function
A function is a group of statements that together perform a task. Every C program has at
least one function, which is main(), and all the most trivial programs can define additional
functions.
You can divide up your code into separate functions. How you divide up your code among
different functions is up to you, but logically the division is such that each function performs
a specific task.
A function declaration tells the compiler about a function's name, return type, and
parameters. A function definition provides the actual body of the function.
The C standard library provides numerous built-in functions that your program can call. For
example, strcat() to concatenate two strings, memcpy() to copy one memory location to
another location, and many more functions.
Features of Function
• Reusability of Code: Means Once a Code has Developed then we can use that Code
any Time.
• Remove Redundancy: Means a user doesn’t need to Write Code Again and Again.
• Decrease Complexity: Means a Large program will be Stored in the Two or More
Functions. So that this will makes easy for a user to understand that Code.
Advantages of Function
Here are several advantages of using functions in your code:
• Use of functions enhances the readability of a program. A big code is always difficult
to read. Breaking the code in smaller Functions keeps the program organized, easy
to understand and makes it reusable.
• The C compiler follows top-to-down execution, so the control flow can be easily
managed in case of functions. The control will always come back to the main()
function.
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
54
For the above defined function max(), the function declaration is as follows −
Parameter names are not important in function declaration only their type is required, so
the following is also a valid declaration −
Function declaration is required when you define a function in one source file and you call
that function in another file. In such case, you should declare the function at the top of the
file calling the function.
Defining a Function
The general form of a function definition in C programming language is as follows −
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
55
Return Type − A function may return a value. The return_type is the data type of the value
the function returns. Some functions perform the desired operations without returning a
value. In this case, the return_type is the keyword void.
Function Name − This is the actual name of the function. The function name and the
parameter list together constitute the function signature.
Function Body − The function body contains a collection of statements that define what the
function does.
Example:
int max(int num1, int num2) {
int result;
result = num1;
else
result = num2;
return result;
Calling a Function:
While creating a C function, you give a definition of what the function has to do. To use a
function, you will have to call that function to perform the defined task.
When a program calls a function, the program control is transferred to the called function. A
called function performs a defined task and when its return statement is executed or when
its function-ending closing brace is reached, it returns the program control back to the main
program.
To call a function, you simply need to pass the required parameters along with the function
name, and if the function returns a value, then you can store the returned value.
For example –
#include <stdio.h>
int main () {
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
56
int a = 100;
int b = 200;
int ret;
return 0;
int result;
result = num1;
else
result = num2;
return result;
We have kept max() along with main() and compiled the source code. While running the
final executable, it would produce the following result –
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
57
Function definition:
void function()
statements;
Example:
#include <stdio.h>
void value(void);
void main()
value();
void value(void)
float sum;
sum = amount;
year = year + 1;
Syntax:
Function definition:
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
58
statements;
Example:
#include <stdio.h>
int main()
int a = 20;
return 0;
inti;
Output:
value of a is 20
value of ar[0] is 10
value of ar[1] is 20
value of ar[2] is 30
value of ar[3] is 40
value of ar[4] is 50
The given string is: Nepalinbeauty
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
59
Function definition:
int function()
{
statements;
return x;
}
Example:
#include <math.h>
#include <stdio.h>
int sum();
int main()
int num;
num = sum();
return 0;
int sum()
return sum;
Output:
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
60
Example:
#include <stdio.h>
#include <string.h>
int function(int, int[]);
int main()
{
inti, a = 20;
intarr[5] = { 10, 20, 30, 40, 50 };
a = function(a, &arr[0]);
printf("value of a is %d\n", a);
for (i = 0; i< 5; i++) {
printf("value of arr[%d] is %d\n", i, arr[i]);
}
return 0;
}
int function(int a, int* arr)
{
inti;
a = a + 20;
arr[0] = arr[0] + 50;
arr[1] = arr[1] + 50;
arr[2] = arr[2] + 50;
arr[3] = arr[3] + 50;
arr[4] = arr[4] + 50;
return a;
}
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
61
Output:
value of a is 40
value of arr[0] is 60
value of arr[1] is 70
value of arr[2] is 80
value of arr[3] is 90
value of arr[4] is 100
1. Library functions
2. User-defined functions
Library functions are those functions which are already defined in C library, example printf(),
scanf(), strcat() etc. You just need to include appropriate header files to use these functions.
These are already declared and defined in C libraries.
A User-defined functions on the other hand, are those functions which are defined by the
user at the time of writing program. These functions are made for code reusability and for
saving time and space.
Example:
int result;
result = num1;
else
result = num2;
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
62
return result;
These function are created by user as These functions are not created by user as
per their own requirement. their own.
User-defined functions are not stored Library Functions are stored in special
in library file. library file.
There is no such kind of requirement In this if the user wants to use a particular
to add the particular library. library function then the user have to add
the particular library of that function in
header file of the program.
Execution of the program begins from Execution of the program does not begin
the user-define function. from the library function.
1. Call by Value
2. Call by Reference
Call by value in C
⚫ In call by value method, the value of the actual parameters is copied into the formal
parameters. In other words, we can say that the value of the variable is used in the
function call in the call by value method.
⚫ In call by value method, we cannot modify the value of the actual parameter by the
formal parameter.
⚫ In call by value, different memory is allocated for actual and formal parameters since
the value of the actual parameter is copied into the formal parameter.
⚫ The actual parameter is the argument which is used in the function call whereas
formal parameter is the argument which is used in the function definition.
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
63
Example:
#include<stdio.h>
num=num+100;
int main() {
int x=100;
return 0;
Output:
Call by reference in C
⚫ In call by reference, the address of the variable is passed into the function call as the
actual parameter.
⚫ The value of the actual parameters can be modified by changing the formal
parameters since the address of the actual parameters is passed.
⚫ In call by reference, the memory allocation is similar for both formal parameters and
actual parameters. All the operations in the function are performed on the value
stored at the address of the actual parameters, and the modified value gets stored at
the same address.
Example:
#include<stdio.h>
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
64
(*num) += 100;
int main() {
int x=100;
return 0;
Output:
The values of actual argument are sent to The reference of actual argument is sent
formal argument which are normal to formal argument which are pointer
variables. variables.
Any changes made by formal arguments Any changes made by formal arguments
will not reflect to actual arguments. will reflect to actual arguments.
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
65
void recursion() {
int main() {
recursion();
The C programming language supports recursion, i.e., a function to call itself. But while using
recursion, programmers need to be careful to define an exit condition from the function,
otherwise it will go into an infinite loop.
Recursive functions are very useful to solve many mathematical problems, such as
calculating the factorial of a number, generating Fibonacci series, etc.
Number Factorial
The following example calculates the factorial of a given number using a recursive function −
#include <stdio.h>
if(i <= 1) {
return 1;
int main() {
int i = 12;
return 0;
Output:
Factorial of 12 is 479001600
Fibonacci Series
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
66
The following example generates the Fibonacci series for a given number using a recursive
function −
#include <stdio.h>
int fibonacci(int i) {
if(i == 0) {
return 0;
if(i == 1) {
return 1;
int main() {
int i;
printf("%d\t\n", fibonacci(i));
return 0;
Output
13
21
34
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
67
Chapter: 5
Array String
Concept of Array
Arrays a kind of data structure that can store a fixed-size sequential collection of elements of
the same type. An array is used to store a collection of data, but it is often more useful to
think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you
declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables. A specific element in an array is accessed by
an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the
first element and the highest address to the last element.
Declaring Arrays
To declare an array in C, a programmer specifies the type of the elements and the number of
elements required by an array as follows −
This is called a single-dimensional array. The arraySize must be an integer constant greater
than zero and type can be any valid C data type. For example, to declare a 10-element array
called balance of type double, use this statement −
double balance[10];
Initializing Arrays
You can initialize an array in C either one by one or using a single statement as follows −
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
68
The number of values between braces { } cannot be larger than the number of elements that
we declare for the array between square brackets [ ].
If you omit the size of the array, an array just big enough to hold the initialization is created.
Therefore, if you write −
You will create exactly the same array as you did in the previous example. Following is an
example to assign a single element of the array −
balance[4] = 50.0;
The above statement assigns the 5th element in the array with a value of 50.0. All arrays
have 0 as the index of their first element which is also called the base index and the last
index of an array will be total size of the array minus 1. Shown below is the pictorial
representation of the array we discussed above −
The above statement will take the 10th element from the array and assign the value to
salary variable. The following example Shows how to use all the three above mentioned
concepts viz. declaration, assignment, and accessing arrays −
#include <stdio.h>
int main () {
int i,j;
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
69
return 0;
Output:
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
String in C
String is an array of characters and terminated by a null character (\0). The null character is
not placed by the user, the compiler places it at the end of string automatically.
The difference between an array and a string is that the compiler does not place null
character at the end of array while in string, compiler places null character.
char myStr[size];
Here,
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
70
Syntax:
Example:
int a[5];
Example
#include<stdio.h>
int main ( ){
int i;
Output
10 20 30 40 50
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
71
Example
#include<stdio.h>
main ( ){
int a[5],i;
scanf("%d", &a[i]);
printf("%d", a[i]);
Output
enter 5 elements 10 20 30 40 50
Note
• The output of compile time initialised program will not change during different runs
of the program.
• The output of run time initialised program will change for different runs because,
user is given a chance of accepting different values during execution.
Example
#include <stdio.h>
int main(void){
int a[4];
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
72
printf("\nArray a:\n");
printf("arr[%d]: %d\n",i,a[i]);
printf("\nArray b:\n");
printf("arr[%d]: %d\n",i,b[i]);
printf("\nArray c:\n");
return 0;
Output
Array a:
arr[0]: 8
arr[1]: 0
arr[2]: 54
arr[3]: 0
Array b:
arr[0]: 1
arr[1]: 0
arr[2]: 0
arr[3]: 0
Array c:
arr[0]: 1
arr[1]: 2
arr[2]: 3
arr[3]: 4
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
73
Declaration:
char[] gets(char[]);
Example:
#include<stdio.h>
void main ()
char s[30];
gets(s);
Output
The gets() function is risky to use since it doesn't perform any array bound checking and
keep reading the characters until the new line (enter) is encountered. It suffers from buffer
overflow, which can be avoided by using fgets(). The fgets() makes sure that not more than
the maximum limit of characters are read. Consider the following example.
#include<stdio.h>
void main()
char str[20];
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
74
printf("%s", str);
Output
javatpoint is the b
C puts() function
The puts() function is very much similar to printf() function. The puts() function is used to
print the string on the console which is previously read by using gets() or scanf() function.
The puts() function returns an integer value representing the number of characters being
printed on the console. Since, it prints an additional newline character with the string, which
moves the cursor to the new line on the console, the integer value returned by puts() will
always be equal to the number of characters present in the string plus 1.
Declaration:
int puts(char[])
Example:
#include<stdio.h>
#include <string.h>
int main(){
char name[50];
return 0;
Output:
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
75
#include<stdio.h>
#include <string.h>
int main(){
char ch[20]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
return 0;
Output:
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
76
#include<stdio.h>
#include <string.h>
int main(){
char ch[20]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
char ch2[20];
strcpy(ch2,ch);
return 0;
Output:
#include<stdio.h>
#include <string.h>
int main(){
strcat(ch,ch2);
return 0;
Output:
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
77
Here, we are using gets() function which reads string from the console.
#include<stdio.h>
#include <string.h>
int main(){
char str1[20],str2[20];
gets(str2);
if(strcmp(str1,str2)==0)
else
return 0;
Output:
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
78
#include<stdio.h>
#include <string.h>
int main(){
char str[20];
return 0;
Output:
#include<stdio.h>
#include <string.h>
int main(){
char str[20];
return 0;
Output:
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
79
#include<stdio.h>
#include <string.h>
int main(){
char str[20];
return 0;
Output:
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
80
Chapter: 6
Structure and Union
Concept of Structure
Structure is a user-defined datatype in C language which allows us to combine data of
different types together. Structure helps to construct a complex data type which is more
meaningful. It is somewhat similar to an Array, but an array holds data of similar type only.
But structure on the other hand, can store data of any type, which is practical more useful.
Structure is a user defined datatype. It is used to combine the different types of data into
single type. It can have multiple members and structure variables. The keyword “struct” is
used to define structures in C language. Structure members can be accessed by using dot(.)
operator.
• It is possible to copy the contents of all structural elements of different data types to
another structure variable of its type by using an assignment operator.
• To handle complex datatypes, it is possible to create a structure within another
structure, which is called nested structures.
• It is possible to pass an entire structure, individual elements of structure, and address of
structure to a function.
• It is possible to create structure pointers.
Concept of Union
Union can be defined as a user-defined data type which is a collection of different variables
of different data types in the same memory location. The union can also be defined as many
members, but only one member can contain a value at a particular point in time.
A union is a special data type available in C that allows to store different data types in the
same memory location. You can define a union with many members, but only one member
can contain a value at any given time. Unions provide an efficient way of using the same
memory location for multiple-purpose.
(i) Efficient use of memory as it does not demand memory space for its all members
rather it require memory space for its largest member only.
(ii) Same memory space can be interpreted differently for different members of the
union.
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
81
member definition;
member definition;
...
The structure tag is optional and each member definition is a normal variable definition,
such as int i; or float f; or any other valid variable definition. At the end of the structure's
definition, before the final semicolon, you can specify one or more structure variables but it
is optional. Here is the way you would declare the Book structure −
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
} book;
Syntax:
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
82
Example:
#include<stdio.h>
struct Point
int x, y;
};
int main()
p1.x = 20;
return 0;
#include <stdio.h>
#include <string.h>
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
83
int main( ) {
/* book 1 specification */
Book1.book_id = 6495407;
/* book 2 specification */
Book2.book_id = 6495700;
return 0;
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
84
Output:
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
data.i = 10;
data.f = 220.5;
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
85
return 0;
Output:
data.i : 1917853763
data.f : 4122360580327794860452759994368.000000
data.str : C Programming
member definition;
member definition;
...
member definition;
The union tag is optional and each member definition is a normal variable definition, such as
int i; or float f; or any other valid variable definition. At the end of the union's definition,
before the final semicolon, you can specify one or more union variables but it is optional.
Here is the way you would define a union type named Data having three members i, f, and
str −
union Data {
int i;
float f;
char str[20];
} data;
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
86
Now, a variable of Data type can store an integer, a floating-point number, or a string of
characters. It means a single variable, i.e., same memory location, can be used to store
multiple types of data. You can use any built-in or user defined data types inside a union
based on your requirement.
The memory occupied by a union will be large enough to hold the largest member of the
union. For example, in the above example, Data type will occupy 20 bytes of memory space
because this is the maximum space which can be occupied by a character string. The
following example displays the total memory size occupied by the above union −
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
return 0;
Output:
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
87
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
88
Chapter-7
Pointers
A pointer is a variable whose value is the address of another variable, i.e., direct address of
the memory location. Like any variable or constant, you must declare a pointer before using
it to store any variable address.
Features of Pointer
• Pointers save memory space.
• An array, of any type, can be accessed with the help of pointers, without considering its
subscript range.
• Pointers are used for file handling.
• Pointers are used to allocate memory dynamically.
Advantages of Pointer
1. Pointers are more efficient in handling Arrays and Structures.
2. Pointers allow references to function and thereby helps in passing of function as
arguments to other functions.
3. It reduces length of the program and its execution time as well.
4. It allows C language to support Dynamic Memory management.
*pointer_name;
or
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
89
datatype* pointer_name;
Data type of a pointer must be same as the data type of the variable to which the pointer
variable is pointing. Void type pointer works with all data types, but is not often used.
Pointer variable always point to variables of same datatype. Let's have an example to
showcase this: #include<stdio.h> void main()
{ float a; int
*ptr;
If you are not sure about which variable's address to assign to a pointer variable while
declaration, it is recommended to assign a NULL value to your pointer variable. A pointer
which is assigned a NULLvalue is called a NULL pointer.
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
90
Referencing means taking the address of an existing variable (using &) to set a pointer
variable. In order to be valid, a pointer has to be set to the address of a variable of the same
type as the pointer, without the asterisk:
p1; c1 =5; p1
=&c1;
//p1 references c1
Dereferencing a pointer means using the * operator (asterisk character) to access the value
stored at a pointer: NOTE: The value stored at the address of the pointer must be a value of
the same type as the type of variable the pointer "points" to, but there is no guarantee this
is the case unless the pointer was set correctly. The type of variable the pointer points to is
the type less the outermost asterisk.
int n1; n1
=*p1;
Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta