Download as pdf or txt
Download as pdf or txt
You are on page 1of 90

1

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.

Based on computer programming language expertise, we can name a computer


programmer as follows −

- 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-

- Machine level language: Machine language is lowest level of programming language.


It
handles binary data i.e., 0’s and 1’s. It directly interacts
with
system.
- Assembly level language: Assembly language is a middle-level language. It consists of
a
set of instructions in a specific format called commands. It
uses symbols to represent field of instructions.

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
2

- High-level language: High-level language uses format or language that is most


familiar
to users. The instructions in this language are called codes or
scripts.

• 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.

There are two types of software −

- System Software
- Application Software
- Utilities Program

1.2 Describe the categories of programming language

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

1. Machine Level Language


The computer can understand only the language of Digital Electronics. Digital Electronics
deals with the presence and absence of voltages. Within the computer there are two logics
can play their role. These logics are −

- Positive Logic − Here presence of voltage will be denoted by 1 and absence of


voltage
will be denoted by 0
- Negative Logic − Here presence of voltage will be denoted by 0 and absence of
voltage
will be denoted by 1

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

2. Assembly Level Language


After machine level language, the next level of development in the evolution of computer
languages was the Assembly Language. Machine level language uses only the binary
language. But on the other hand, assembly language uses mnemonics or symbolic
instructions in place of a sequence of 0s and 1s. As fewer examples, we can consider that to
add register A and B in a particular computer, assembly language uses the mnemonic ‘ADD
B’ in place of 10001111. In assembly language, we use symbolic names to denote addresses
and data. A number of such examples are dealt with in the successive chapters. Thus, writing
a program in assembly language has advantages over writing the same in a machine
language.

3. High Level Language


High level language is the next development in the evolution of computer languages.
Examples of some high-level languages are given below:

- PROLOG (for “PROgramming LOGic”)


- FORTRAN (for ‘FORrmula TRANslation’)
- LISP (for “LISt Processing”)
- Pascal (named after the French scientist Blaise Pascal).

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.

4. Structure Oriented Language


These languages belong to the third-generation language. These programs focus on
the logic of the program rather than the hardware architecture. These languages are
machine independent and the program developed on one computer can be used in
another computer. E.g., of these languages are C, COBOL, ALGOL etc.

The advantages of these languages are as follows:

1. It is easy to learn, develop and understand the problems.


2. The programs developed on this language can be executed on other computers.
3. Program are easy to code and debug
4. Program written are less prone to error.

The disadvantages of these language are as follows

1. The program execution is slow


2. The program needs to be converted to machine code so additional language
translator is required
3. Uses computer resources less efficiently
4. The memory requirement of the program written will be more compared to 1GL and
2GL

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
4

5. Problem Oriented Language/ Object Oriented Language


This language is also termed as fourth generation language. Most of the languages
are general purpose programming languages and can be used to develop any kinds
of software for any platform. These programs developed in this language are based
on real world scenario.

The advantages of these languages are as follows

1. These languages are easy to learn and use


2. The debugging and coding are made easier
3. It is more user friendly.
4. The programs developed in these languages are machine independent.

The disadvantages of these languages are as follows

1. The execution speed of the program is slower


2. It needs additional software to convert the program to machine code
3. The memory requirement of the program is high compared to other
4. programming languages

1.3 Elaborate The Programming Dimension Such as


Scientific Application, Business Application

• 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

1.4 Explain The Program Design Tools (Algorithm and


Flowchart)

Program Design Tools


The program design tools are the tools required to develop a program. During
designing the program various tools are required to design the program such as

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

Algorithm for adding two numbers –

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

Flowchart for adding two numbers –

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.

Pseudocode for finding the area of rectangle -

Input number1 number2


Calculate sum = number1 + number2
Output: sum

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

An ancestor of C is Basic Combined Programming Language (BCPL). Ken Thompson, a Bell


Laboratory scientist, developed a version of BCPL, which he called ‘B’. Dennis Ritchie,
another computer scientist, developed a version called ‘C’ in early 1970s that is modified
and improved BCPL. Ritchie originally wrote the language for programming under UNIX
operating system. Later Bell Laboratories rewrote UNIX entirely in C. C belongs to the third-
generation programming language and it is also termed as high level or middle level
language. Out of five generations it lies in third generation.

C is a structured programming language, which means that it allows you to develop


programs using well-defined control structures (you will learn about control structures in the
articles to come), and provides modularity (breaking the task into multiple sub tasks that are
simple enough to understand and to reuse). C is often called a middle-level language
because it combines the best elements of low-level or machine language with high-level
languages. It is one of the most popular programming languages till date due to its speed
and flexibility.

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.

Faster and efficient


C is desirable because it is faster and more efficient than comparable programs in most
other high-level languages. For e.g., a program to increment a variable from 0 to 15000 takes
about 50 seconds in BASIC while it takes 1 second in C.

Supports Structured Programming


It is well suited for structured programming that means, the problem might be solved in
terms of function modules or blocks. The modular structure makes program debugging,
testing and maintenance easier.

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

2.2 Demonstrate the Program Structure and Syntax with


terms Pre-Processor Directive, Header Files, Tokens,

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
10

Semicolons Comments, Identifiers, Whitespace, Escape


Sequence)

Basic Structure of C Programming


The basic structure of a C program comprises the following sections:

- Documentation Section
- Preprocessor Directive Section
- Global Declaration Section
- Main Program Section
- Sub Program Section

The program to demonstrate all those sections as follows:

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 –

Sn. No. Directive & Description


1
#define
Substitutes a preprocessor macro.
2
#include
Inserts a particular header from another file.
3
#undef

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
12

Undefines a preprocessor macro.


4
#ifdef
Returns true if this macro is defined.
5
#ifndef
Returns true if this macro is not defined.
6
#if
Tests if a compile time condition is true.
7
#else
The alternative for #if.
8
#elif
#else and #if in one statement.
9
#endif
Ends preprocessor conditional.
10
#error
Prints error message on stderr.
11
#pragma
Issues special commands to the compiler, using a standardized
method.

Some preprocessors examples,

Analyze the following examples to understand various directives.

#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,

Sn. No. Header Files & Description


1 stdio.h
Input/Output functions
2 conio.h
Console Input/Output functions
3 stdlib.h
General utility functions
4 math.h
Mathematics functions
5 string.h
String functions
6 ctype.h
Character handling functions
7 time.h
Date and time functions
8 float.h
Limits of float types
9 limits.h
Size of basic types
10 wctype.h
Functions to determine the type contained in wide character data.

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("Hello, World! \n");

The individual tokens are:

printf

"Hello, World! \n"

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

Given below are two different statements:

printf("Hello, World! \n");

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 //.

// This is single line comment

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:

mohd zara abc move_name a_123

myname50 _temp j a23b9 retVal

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:

fruit = apples + oranges; // get the total fruit

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 −

Sn. No. Escape Sequence & Description


1 \t Inserts a tab in the text at this point.
2 \b Inserts a backspace in the text at this point.
3 \n Inserts a newline in the text at this point.
4 \r Inserts a carriage return in the text at this point.
5 \f Inserts a form feed in the text at this point.
6 \’ Inserts a single quote character in the text at this point.
7 \” Inserts a double quote character in the text at this point.
8 \\ Inserts a backslash character in the text at this point.

2.3 Describe the Variables and Keywords of C


Programming
Variables
A variable definition tells the compiler where and how much storage to create for the
variable.

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 –

Sn. No. Type & Description


1
char
Typically a single octet(one byte). It is an integer type.
2
int

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
16

The most natural size of integer for the machine.


3
float
A single-precision floating point value.
4
double
A double-precision floating point value.
5
void
Represents the absence of type.

A variable definition specifies a data type and contains a list of one or more variables of that
type as follows −

type variable_list;

type variable_lilst = value;

Example of Variable Decleration

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.

There is total 32 keywords in C.

auto double int struct


break else long switch
case enum register typedef
char extern return union
continue for signed void
do if static while
default goto sizeof volatile
const float short unsigned

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
17

2.4 Elaborate the Character’s Sets, Constants and Variables


Character Sets
The C character sets are used to form words, numbers and expressions. Different categories
of character sets are – letters, digits and special characters.

Letters – upper case: A…Z

Lower case: a…z

Digits – 0…9

Special characters: ‘ “ , . : ; { } [ ] ! # $ & ^ ( ) _ - + * <> ? / \ | !

White spaces: blank \b, tab \t, newline \n

Constant
Constants are fixed values that cannot be altered by the program and can be

numbers, characters or strings.

Some Examples: -

char: 'a', '$', '7'

int: 10, 100, -100

unsigned: 0, 255

float: 12.23456, -1.573765e10, 1.347654E-13

double: 1433.34534545454, 1.35456456456456E-200

long: 65536, 2222222

string: “Hello World\n”

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).

All C variables must be declared as follows: -

datatype variable-list;

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
18

For Example: -

int i;

char a, b, ch;

2.5 Illustrate the Data Types and Format Specifies


Data Types
The first thing we need to know is that we can create variables to store values in. A variable
is just a named area of storage that can hold a single value (numeric or character). C is very
fussy about how you create variables and what you store in them. It demands that you
declare the name of each variable that you are going to use and its type, before you actually
try to do anything with it. Hence, data type can be defined as the storage representation and
machine instruction to handle constants and variables.

There are four basic data types associated with variables:

- 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

3. Floating Point Type


a. float
b. double
c. longdouble

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 variable name;


For example:

int a;

• declares that you want to create an int variable called a.


• float - floating point or real value, i.e., a number with a fractional part.
• double - a double-precision floating point value.
• char - a single character.

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

short int 2 -32,768 to 32,767 %hd


unsigned short int 2 0 to 65,535 %hu

unsigned int 4 0 to 4,294,967,295 %u


int 4 -2,147,483,648 to 2,147,483,647 %d
long int 4 -2,147,483,648 to 2,147,483,647 %ld
unsigned long 4 0 to 4,294,967,295 %lu
int

long longint 8 -(2^63) to (2^63)-1 %lld

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
20

unsigned long 8 0 to 18,446,744,073,709,551,615 %llu


longint

signed char 1 -128 to 127 %c


unsigned char 1 0 to 255 %c
float 4 %f
double 8 %lf
long double 12 %Lf

Derived Data Type


Different user defined data type can be created using fundamental data types which are
called derived data type.

Array, structure, union and functions are derived data types.

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.

2.6 Describe Input/Output Statements of C


When we say Input, it means to feed some data into a program. An input can be given in the
form of a file or from the command line. C programming provides a set of built-in functions
to read the given input and feed it to the program as per requirement.

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 Standard Files


C programming treats all the devices as files. So, devices such as the display are addressed in
the same way as files and the following three files are automatically opened when a
program executes to provide access to the keyboard and screen.

Standard File File Pointer Device


Standard input stdin Keyboard
Standard output stdout Screen
Standard error stderr Your screen

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 getchar() and putchar() Functions


The int getchar(void) function reads the next available character from the screen and returns
it as an integer. This function reads only single character at a time. You can use this method
in the loop in case you want to read more than one character from 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;

printf( "Enter a value :");

c = getchar( );

printf( "\nYou entered: ");

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 −

Enter a value : this is test

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
22

You entered: t

The gets() and puts() Functions


The char *gets(char *s) function reads a line from stdin into the buffer pointed to by s until
either a terminating newline or EOF (End of File).

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];

printf( "Enter a value :");

gets( str );

printf( "\nYou entered: ");

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 –

Enter a value : this is test

You entered: this is test

The scanf() and printf() Functions


The int scanf(const char *format, ...) function reads the input from the standard input
stream stdin and scans that input according to the format provided.

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;

printf( "Enter a value :");

scanf("%s %d", str, &i);

printf( "\nYou entered: %s %d ", str, 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 −

Enter a value : seven 7

You entered: seven 7

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().

2.7 Describe the operators in C such as


(Arithmeticoperator, Relational Operator, Logical
operator, Bitwise operator, Assignment operator)

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

Operator Description Example

+ Adds two operands. A + B = 30

− Subtracts second operand from the first. A − B = -10

* Multiplies both operands. A * B = 200

/ Divides numerator by de-numerator. B/A=2

% Modulus Operator and remainder of after an integer division. B%A=0

++ Increment operator increases the integer value by one. A++ = 11

-- Decrement operator decreases the integer value by one. A-- = 9

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

printf("Line 6 - Value of c is %d\n", c );

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 −

Operator Description Example

== 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" );
}

/* Lets change value of a and b */


a = 5;
b = 20;

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 −

Operator Description Example

&& 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 OR Operator. If any of the two operands is non- (A || B) is true.


zero, then the condition becomes true.

! 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");
}

/* lets change the value of a and b */


a = 0;
b = 10;

if (a && b)
{
printf("Line 3 - Condition is true\n");
}
else
{
printf("Line 3 - Condition is not true\n");
}

if (!(a && b))


{
printf("Line 4 - Condition is 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.

Operator Description Example

& Binary AND Operator copies a bit to the result if it exists in both (A & B) = 12, i.e.,
operands. 0000 1100

| Binary OR Operator copies a bit if it exists in either operand. (A | B) = 61, i.e.,


0011 1101

^ Binary XOR Operator copies the bit if it is set in one operand but (A ^ B) = 49, i.e.,
not both. 0011 0001

~ (~A ) = ~(60), i.e,. -


Binary One's Complement Operator is unary and has the effect 0111101
of 'flipping' bits.

<< 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()
{

unsigned int a = 60; /* 60 = 0011 1100 */


unsigned int b = 13; /* 13 = 0000 1101 */
int c = 0;

c = a & b; /* 12 = 0000 1100 */


printf("Line 1 - Value of c is %d\n", c);

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);

c = ~a; /*-61 = 1100 0011 */


printf("Line 4 - Value of c is %d\n", c);

c = a << 2; /* 240 = 1111 0000 */


printf("Line 5 - Value of c is %d\n", c);

c = a >> 2; /* 15 = 0000 1111 */


printf("Line 6 - Value of c is %d\n", c);
}

Assignment Operators
The following table lists the assignment operators supported by the C language −

Operator Description Example

= Simple assignment operator. Assigns values from right


side operands to left side operand
C = A + B will assign the
value of A + B to C

+= Add AND assignment operator. It adds the right operand


to the left operand and assign the result to the left C += A is equivalent to C =
operand. C+A

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
30

-= Subtract AND assignment operator. It subtracts the right


C -= A is equivalent to C = C
operand from the left operand and assigns the result to
-A
the left operand.

*= Multiply AND assignment operator. It multiplies the right


operand with the left operand and assigns the result to C *= A is equivalent to C =
the left operand. C*A

/= Divide AND assignment operator. It divides the left


operand with the right operand and assigns the result to C /= A is equivalent to C = C
the left operand. /A

%= Modulus AND assignment operator. It takes modulus


using two operands and assigns the result to the left C %= A is equivalent to C =
operand. C%A

<<= Left shift AND assignment operator. C <<= 2 is same as C = C <<


2

>>= Right shift AND assignment operator. C >>= 2 is same as C = C >>


2

&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2

^= Bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2

|= Bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2

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

3.1 Introduce the Decision-Making 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.

C programming language provides the following types of decision-making statements.

Sn. No. Statement & Description

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
33

if statement

1 An if statement consists of a boolean expression followed by one or


more statements.

if...else statement

2 An if statement can be followed by an optional else statement, which


executes when the Boolean expression is false.

nested if statements

3 You can use one if or else if statement inside another if or else


if statement(s).

switch statement

4 A switch statement allows a variable to be tested for equality against a


list of values.

nested switch statements


5 You can use one switch statement inside another switch statement(s).

3.2 Demonstrate the If, If Else, Else If…Else Statement and


Switch Statement and their Conditions

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 ) {

printf("a is less than 20\n" );

} else {

printf("a is not less than 20\n" );

printf("value of a is: %d\n", a);

return 0;

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
36

Output:
a is not less than 20;

value of a is: 100

If elseif else Statement:


An if statement can be followed by an optional else if...else statement, which is very useful
to test various conditions using single if...else if statement.

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) {

/* Executes when the boolean expression 1 is true */

} else if( boolean_expression 2) {

/* Executes when the boolean expression 2 is true */

} else if( boolean_expression 3) {

/* Executes when the boolean expression 3 is true */

} else {

/* executes when the none of the above condition is true */

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 {

printf("None of the values is matching\n" );

printf("Exact value of a is: %d\n", a );

return 0;

Output:
None of the values is matching

Exact value of a is: 100

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;

case constant-expression (N):

statement(s);

break;

default:

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
38

statement(s);

The following rules apply to a switch statement −

• The expression used in a switch statement must have an integral or enumerated


type, or be of a class type in which the class has a single conversion function to an
integral or enumerated type.
• You can have any number of case statements within a switch. Each case is followed
by the value to be compared to and a colon.
• The constant-expression for a case must be the same data type as the variable in the
switch, and it must be a constant or a literal.
• When the variable being switched on is equal to a case, the statements following
that case will execute until a break statement is reached.
• When a break statement is reached, the switch terminates, and the flow of control
jumps to the next line following the switch statement.
• Not every case needs to contain a break. If no break appears, the flow of control will
fall through to subsequent cases until a break is reached.
• A switch statement can have an optional default case, which must appear at the end
of the switch. The default case can be used for performing a task when none of the
cases is true. No break is needed in the default case.

Flow Diagram:

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
39

Example:
#include <stdio.h>

int main () {

char grade = 'B';

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' :

printf("Better try again\n" );

break;

default :

printf("Invalid grade\n" );

printf("Your grade is %c\n", grade );

return 0;

Output:
Well done

Your grade is B

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
40

3. 3 Describe the Loop Statements with its Necessity


You may encounter situations, when a block of code needs to be executed several numbers
of times. In general, statements are executed sequentially: The first statement in a function
is executed first, followed by the second, and so on.

Programming languages provide various control structures that allow for more complicated
execution paths.

A loop statement allows us to execute a statement or group of statements multiple times.


Given below is the general form of a loop statement in most of the programming languages

C programming language provides the following types of loops to handle looping


requirements.

Sn. No. Loop Type & Description


while loop
1 Repeats a statement or group of statements while a given condition is
true. It tests the condition before executing the loop body.

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

3 It is more like a while statement, except that it tests the condition at


the end of the loop body.

nested loops
4 You can use one or more loops inside any other while, for, or do while
loop.

3.4 Demonstrate the For Loop, While Loop and Do-While


Loop Statement and Nested Loop Statement with its
Conditions
While Loop
A while loop in C programming repeatedly executes a target statement as long as a given
condition is true.

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 ) {

printf("value of a: %d\n", a);

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

Here is the flow of control in a 'for' loop −

• 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;

for( a = 10; a < 20; a = a + 1 ){

printf("value of a: %d\n", 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 {

printf("value of a: %d\n", a);

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 ) {

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;

for(i = 2; i<100; i++) {

for(j = 2; j <= (i/j); j++)

if(!(i%j)) break; // if factor found, not prime

if(j > (i/j)) printf("%d is prime\n", i);

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

3.5 Illustrate Jump Statement


Loop Control Statements
Loop control statements change execution from its normal sequence. When execution
leaves a scope, all automatic objects that were created in that scope are destroyed.

C supports the following control statements.

Sn. No. Control Statement & Description


break statement
1 Terminates the loop or switch statement and transfers execution to the
statement immediately following the loop or switch.
continue statement
2 Causes the loop to skip the remainder of its body and immediately retest its
condition prior to reiterating.
goto statement
3
Transfers control to the labeled statement.

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
49

3.6 Demonstrate the break, continue, goto And return


Statement with its Conditions
Break Statement:
The break statement in C programming has the following two usages −

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 ) {

printf("value of a: %d\n", a);

a++;

if( a > 15) {

/* terminate the loop using break statement */

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) {

/* skip the iteration */

a = a + 1;

continue;

printf("value of a: %d\n", a);

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

4.1 Introduce the Concept of Function in C and its Features


and Advantages

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.

A function can also be referred as a method or a sub-routine or a procedure, etc.

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

• It reduces the complexity of a program and gives it a modular structure.


• In case we need to test only a particular part of the program we will have to run the
whole program and figure out the errors which can be quite a complex process.
Another advantage here is that functions can be individually tested which is more
convenient than the above mentioned process.
• A function can be used to create our own header file which can be used in any
number of programs i.e. the reusability.

4.2 Demonstrate the declaration of a function, defining of


a function and the calling of a function
Function Declarations
A function declaration tells the compiler about a function name and how to call the function.
The actual body of the function can be defined separately.

A function declaration has the following parts −

return_type function_name( parameter list );

For the above defined function max(), the function declaration is as follows −

int max(int num1, int num2);

Parameter names are not important in function declaration only their type is required, so
the following is also a valid declaration −

int max(int, int);

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 −

return_type function_name( parameter list ) {

body of the function

A function definition in C programming consists of a function header and a function body.


Here are all the parts of a function −

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.

Parameters − A parameter is like a placeholder. When a function is invoked, you pass a


value to the parameter. This value is referred to as actual parameter or argument. The
parameter list refers to the type, order, and number of the parameters of a function.
Parameters are optional; that is, a function may contain no parameters.

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;

if (num1 > num2)

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 max(int num1, int num2);

int main () {

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
56

int a = 100;

int b = 200;

int ret;

ret = max(a, b);

printf( "Max value is : %d\n", ret );

return 0;

/* function returning the max between two numbers */

int max(int num1, int num2) {

int result;

if (num1 > num2)

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 –

Max value is : 200

4.3 Discuss different types of functions


Function Types
A function in C can be called either with arguments or without arguments. These functions
may or may not return values to the calling functions. All C functions can be called either
with arguments or without arguments in a C program. Also, they may or may not return any
values. Hence the function prototype of a function in C is as below:

1. Function with no argument and no return value:


When a function has no arguments, it does not receive any data from the calling
function. Similarly, when it does not return a value, the calling function does not receive
any data from the called function.
Syntax:
Function declaration: void function();

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
57

Function call: function();

Function definition:

void function()

statements;

Example:

#include <stdio.h>

void value(void);

void main()

value();

void value(void)

int year = 1, period = 5, amount = 5000, inrate = 0.12;

float sum;

sum = amount;

while (year <= period) {

sum = sum * (1 + inrate);

year = year + 1;

printf(" The total amount is %f:", sum);

Output: The total amount is 5000.000000

2. Function with arguments but no return value:


When a function has arguments, it receives any data from the calling function but it
returns no values.

Syntax:

Function declaration: void function ( int );

Function call : function( x );

Function definition:

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
58

void function( int x )

statements;

Example:

#include <stdio.h>

void function(int, int[], char[]);

int main()

int a = 20;

intar[5] = { 10, 20, 30, 40, 50 };

char str[30] = "Nepalinbeauty";

function(a, &ar[0], &str[0]);

return 0;

void function(int a, int* ar, char* str)

inti;

printf("value of a is %d\n\n", a);

for (i = 0; i< 5; i++) {

printf("value of ar[%d] is %d\n", i, ar[i]);

printf("\nvalue of str is %s\n", str);

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

3. Function with no arguments but returns a value:


There could be occasions where we may need to design functions that may not take any
arguments but returns a value to the calling function. An example for this is getchar
function it has no parameters but it returns an integer an integer type data that
represents a character.
Syntax:
Function declaration: int function();

Function call: function();

Function definition:

int function()
{
statements;
return x;
}

Example:

#include <math.h>

#include <stdio.h>

int sum();

int main()

int num;

num = sum();

printf("\nSum of two given values = %d", num);

return 0;

int sum()

int a = 50, b = 80, sum;

sum = sqrt(a) + sqrt(b);

return sum;

Output:

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
60

Sum of two given values = 16

4. Function with arguments and return value Syntax:


Syntax:
Function declaration : int function ( int );
Function call : function( x );
Function definition:
int function( int x )
{
statements;
return x;
}

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

4.4 Explain Library function vs User Defined function


C functions can be classified into two categories,

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 min(int num1, int num2) {

int result;

if (num1 < num2)

result = num1;

else

result = num2;

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
62

return result;

The differences between the function are:

User-defined Functions Library Functions


These functions are not predefined in These functions are predefined in the
the Compiler. compiler of C language.

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.

Example: sum(), fact(),…etc. Example: printf(), scanf(), sqrt(),…etc.

4.5 Introduce the function call (Call by value , Call by


reference)
There are two methods to pass the data into the function in C language, i.e., call by value
and call by reference.

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>

void change(int num) {

printf("Before adding value inside function num=%d \n",num);

num=num+100;

printf("After adding value inside function num=%d \n", num);

int main() {

int x=100;

printf("Before function call x=%d \n", x);

change(x);//passing value in function

printf("After function call x=%d \n", x);

return 0;

Output:

Before function call x=100

Before adding value inside function num=100

After adding value inside function num=200

After function call x=100

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>

void change(int *num) {

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
64

printf("Before adding value inside function num=%d \n",*num);

(*num) += 100;

printf("After adding value inside function num=%d \n", *num);

int main() {

int x=100;

printf("Before function call x=%d \n", x);

change(&x);//passing reference in function

printf("After function call x=%d \n", x);

return 0;

Output:

Before function call x=100

Before adding value inside function num=100

After adding value inside function num=200

After function call x=200

Difference between call by value and call by reference.

Call by Value Call by Reference


The actual arguments can be variable or The actual arguments can only be
constant. variable.

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.

4.6 Describe the concept of recursive functions


Recursion is the process of repeating items in a self-similar way. In programming languages,
if a program allows you to call a function inside the same function, then it is called a
recursive call of the function.

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
65

void recursion() {

recursion(); /* function calls itself */

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>

unsigned long long int factorial(unsigned int i) {

if(i <= 1) {

return 1;

return i * factorial(i - 1);

int main() {

int i = 12;

printf("Factorial of %d is %d\n", i, factorial(i));

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;

return fibonacci(i-1) + fibonacci(i-2);

int main() {

int i;

for (i = 0; i < 10; 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

5.1 Introduce the concept of Arrays& Strings in C

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 −

type arrayName [ arraySize ];

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];

Here balance is a variable array which is sufficient to hold up to 10 double numbers.

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

double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};

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 −

double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};

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 −

Accessing Array Elements


An element is accessed by indexing the array name. This is done by placing the index of the
element within square brackets after the name of the array. For example −

double salary = balance[9];

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 n[ 10 ]; /* n is an array of 10 integers */

int i,j;

/* initialize elements of array n to 0 */

for ( i = 0; i < 10; i++ ) {

n[ i ] = i + 100; /* set element at location i to i + 100 */

/* output each array element's value */

for (j = 0; j < 10; j++ ) {

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
69

printf("Element[%d] = %d\n", j, n[j] );

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.

Here is the syntax of string in C language,

char myStr[size];

Here,

myStr: The string

size: Set the size of string

Initialize string in C language like show below −

char myStr[size] = “string”;

char myStr[size] = { ‘s’,’t’,’r’,’i’,’n’,’g’,’\0’ };

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
70

5.2 Describe the features of arrays


Arrays commonly have the following features:

• An element type. All elements of an array are of the same type.


• An index range. Elements of an array are accessed using an index value. Each array
element has a unique associated index value.
• A length. The length of the array is the number of elements in the array.
• A size. The size of the array is the size of all the elements in the array. This can be
expressed mathematically as Length * Element_Size where Length is the number of
elements in the array and Element_Size is the memory size of an individual element.
• A name for the array object.

5.3 Elaborate One dimensional Array


An array is a group of related items that store with a common name.

Syntax:

The syntax is as follows for declaring an array −

datatype array_name [size];

Example:

int a[5];

Example

#include<stdio.h>

int main ( ){

int a[5] = {10,20,30,40,50};

int i;

printf ("elements of the array are");

for ( i=0; i<5; i++)

printf ("%d", a[i]);

Output

Upon execution, you will receive the following output −

Elements of the array are

10 20 30 40 50

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
71

Example

Following is the C program on runtime initialization –

#include<stdio.h>

main ( ){

int a[5],i;

printf ("enter 5 elements");

for ( i=0; i<5; i++)

scanf("%d", &a[i]);

printf("elements of the array are");

for (i=0; i<5; i++)

printf("%d", a[i]);

Output

The output is as follows −

enter 5 elements 10 20 30 40 50

elements of the array are : 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];

int b[4] = {1};

int c[4] = {1,2,3,4};

int i; //for loop counter

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
72

//printing all elements of all arrays

printf("\nArray a:\n");

for( i=0; i<4; i++ )

printf("arr[%d]: %d\n",i,a[i]);

printf("\nArray b:\n");

for( i=0; i<4; i++)

printf("arr[%d]: %d\n",i,b[i]);

printf("\nArray c:\n");

for( i=0; i<4; i++ )

printf("arr[%d]: %d\n",i, c[i]);

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

5.4 Demonstrate the usage of gets() and puts() functions


C gets() function
The gets() function enables the user to enter some characters followed by the enter key. All
the characters entered by the user get stored in a character array. The null character is
added to the array to make it a string. The gets() allows the user to enter the space-
separated strings. It returns the string entered by the user.

Declaration:

char[] gets(char[]);

Example:

#include<stdio.h>

void main ()

char s[30];

printf("Enter the string? ");

gets(s);

printf("You entered %s",s);

Output

Enter the string?

javatpoint is the best

You entered javatpoint is the best

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];

printf("Enter the string? ");

fgets(str, 20, stdin);

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
74

printf("%s", str);

Output

Enter the string? javatpoint is the best website

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];

printf("Enter your name: ");

gets(name); //reads string from user

printf("Your name is: ");

puts(name); //displays string

return 0;

Output:

Enter your name: Samiksha

Your name is: Samiksha

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
75

5.5 Demonstrate the usage of string functions strlen()


,strcpy(), strcat(), strcmp(),strrev(), strlwr(), strupr()

There are many important string functions defined in "string.h" library.

No. Function Description


1) strlen(string_name) returns the length of string name.
2) strcpy(destination, copies the contents of source string to
source) destination string.
3) strcat(first_string, concats or joins first string with second string.
second_string) The result of the string is stored in first string.
4) strcmp(first_string, compares the first string with second string. If
second_string) both strings are same, it returns 0.
5) strrev(string) returns reverse string.
6) strlwr(string) returns string characters in lowercase.
7) strupr(string) returns string characters in uppercase.

C String Length: strlen() function


The strlen() function returns the length of the given string. It doesn't count null character
'\0'.

#include<stdio.h>

#include <string.h>

int main(){

char ch[20]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};

printf("Length of string is: %d",strlen(ch));

return 0;

Output:

Length of string is: 10

C Copy String: strcpy()

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
76

The strcpy(destination, source) function copies the source string in destination.

#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);

printf("Value of second string is: %s",ch2);

return 0;

Output:

Value of second string is: javatpoint

C String Concatenation: strcat()


The strcat(first_string, second_string) function concatenates two strings and result is
returned to first_string.

#include<stdio.h>

#include <string.h>

int main(){

char ch[10]={'h', 'e', 'l', 'l', 'o', '\0'};

char ch2[10]={'c', '\0'};

strcat(ch,ch2);

printf("Value of first string is: %s",ch);

return 0;

Output:

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
77

Value of first string is: helloc

C Compare String: strcmp()


The strcmp(first_string, second_string) function compares two string and returns 0 if both
strings are equal.

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];

printf("Enter 1st string: ");

gets(str1);//reads string from console

printf("Enter 2nd string: ");

gets(str2);

if(strcmp(str1,str2)==0)

printf("Strings are equal");

else

printf("Strings are not equal");

return 0;

Output:

Enter 1st string: hello

Enter 2nd string: hello

Strings are equal

C Reverse String: strrev()


The strrev(string) function returns reverse of the given string. Let's see a simple example of
strrev() function.

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
78

#include<stdio.h>

#include <string.h>

int main(){

char str[20];

printf("Enter string: ");

gets(str);//reads string from console

printf("String is: %s",str);

printf("\nReverse String is: %s",strrev(str));

return 0;

Output:

Enter string: javatpoint

String is: javatpoint

Reverse String is: tnioptavaj

C String Lowercase: strlwr()


The strlwr(string) function returns string characters in lowercase. Let's see a simple example
of strlwr() function.

#include<stdio.h>

#include <string.h>

int main(){

char str[20];

printf("Enter string: ");

gets(str);//reads string from console

printf("String is: %s",str);

printf("\nLower String is: %s",strlwr(str));

return 0;

Output:

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
79

Enter string: JAVATpoint

String is: JAVATpoint

Lower String is: javatpoint

C String Uppercase: strupr()


The strupr(string) function returns string characters in uppercase. Let's see a simple example
of strupr() function.

#include<stdio.h>

#include <string.h>

int main(){

char str[20];

printf("Enter string: ");

gets(str);//reads string from console

printf("String is: %s",str);

printf("\nUpper String is: %s",strupr(str));

return 0;

Output:

Enter string: Sweta

String is: Sweta

Upper String is: SWETA

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
80

Chapter: 6
Structure and Union

6.1 Introduce the concept of structure & union and their


features

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.

The features of structure are:

• 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.

The features of Union are:

(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

6.2 Demonstrate the declaration of structure and structure


variable
Declaration of a Structure
To define a structure, you must use the struct statement. The struct statement defines a
new data type, with more than one member. The format of the struct statement is as
follows −

struct [structure tag] {

member definition;

member definition;

...

member define tion;

} [one or more structure variables];

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;

Declaration of Structure Variable


A structure variable can either be declared with structure declaration or as a separate
declaration like basic types.

Syntax:

struct [structure tag] variable_name;

struct [structure tag] variable_name = {assign_Value1,assign_value2,assign_value n};

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
82

Example:

#include<stdio.h>

struct Point

int x, y;

};

int main()

struct Point p1 = {0, 1};

// Accessing members of point p1

p1.x = 20;

printf ("x = %d, y = %d", p1.x, p1.y);

return 0;

6.3 Elaborate the member access of structure & union


Member Access of Structure
To access any member of a structure, we use the member access operator (.). The member
access operator is coded as a period between the structure variable name and the structure
member that we wish to access. You would use the keyword struct to define variables of
structure type. The following example shows how to use a structure in a program −

#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( ) {

struct Books Book1; /* Declare Book1 of type Book */

struct Books Book2; /* Declare Book2 of type Book */

/* book 1 specification */

strcpy( Book1.title, "C Programming");

strcpy( Book1.author, "Alisha");

strcpy( Book1.subject, "C Programming Tutorial");

Book1.book_id = 6495407;

/* book 2 specification */

strcpy( Book2.title, "Telecom Billing");

strcpy( Book2.author, "Riya");

strcpy( Book2.subject, "Telecom Billing Tutorial");

Book2.book_id = 6495700;

/* print Book1 info */

printf( "Book 1 title : %s\n", Book1.title);

printf( "Book 1 author : %s\n", Book1.author);

printf( "Book 1 subject : %s\n", Book1.subject);

printf( "Book 1 book_id : %d\n", Book1.book_id);

/* print Book2 info */

printf( "Book 2 title : %s\n", Book2.title);

printf( "Book 2 author : %s\n", Book2.author);

printf( "Book 2 subject : %s\n", Book2.subject);

printf( "Book 2 book_id : %d\n", Book2.book_id);

return 0;

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
84

Output:

Book 1 title : C Programming

Book 1 author : Alisha

Book 1 subject : C Programming Tutorial

Book 1 book_id : 6495407

Book 2 title : Telecom Billing

Book 2 author : Riya

Book 2 subject : Telecom Billing Tutorial

Book 2 book_id : 6495700

Member Access of Union


To access any member of a union, we use the member access operator (.). The member
access operator is coded as a period between the union variable name and the union
member that we wish to access. You would use the keyword union to define variables of
union type. The following example shows how to use unions in a program −

#include <stdio.h>

#include <string.h>

union Data {

int i;

float f;

char str[20];

};

int main( ) {

union Data data;

data.i = 10;

data.f = 220.5;

strcpy( data.str, "C Programming");

printf( "data.i : %d\n", data.i);

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
85

printf( "data.f : %f\n", data.f);

printf( "data.str : %s\n", data.str);

return 0;

Output:

data.i : 1917853763

data.f : 4122360580327794860452759994368.000000

data.str : C Programming

6.4 Demonstrate the declaration of union and union


variable
To define a union, you must use the union statement in the same way as you did while
defining a structure. The union statement defines a new data type with more than one
member for your program. The format of the union statement is as follows −

union [union tag] {

member definition;

member definition;

...

member definition;

} [one or more union variables];

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( ) {

union Data data;

printf( "Memory size occupied by data : %d\n", sizeof(data));

return 0;

Output:

Memory size occupied by data : 20

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
87

6.5 Differentiate between structure and union


Structure Union
You can use a struct keyword to define a You can use a union keyword to define a union.
structure.
Every member within structure is assigned a In union, a memory location is shared by all the
unique memory location. data members.
Changing the value of one data member will not Changing the value of one data member will
affect other data members in structure. change the value of other data members in
union.
It enables you to initialize several members at It enables you to initialize only the first member
once. of union.
The total size of the structure is the sum of the The total size of the union is the size of the
size of every data member. largest data member.
It is mainly used for storing various data types. It is mainly used for storing one of the many data
types that are available.
It occupies space for each and every member It occupies space for a member having the
written in inner parameters. highest size written in inner parameters.
You can retrieve any member at a time. You can access one member at a time in the
union.
It supports flexible array. It does not support a flexible array.

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
88

Chapter-7
Pointers

7.1 Introduce the concept of pointer, its features and


advantages
Concept of Pointer
Pointers in C are easy and fun to learn. Some C programming tasks are performed more
easily with pointers, and other tasks, such as dynamic memory allocation, cannot be
performed without using pointers. So, it becomes necessary to learn pointers to become a
perfect C programmer. Let's start learning them in simple and easy steps.

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.

7.2 Demonstrate the declaration of pointer and pointer


variable
Declaration of pointer variable
Syntax:

*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.

Here are a few examples:


int *ip // pointer to integer variable float *fp;//
pointer to float variable double *dp;// pointer to
double variable char *cp;// pointer to char
variable

Initialization of Pointer variable


Pointer Initialization is the process of assigning address of a variable to a pointer variable.
Pointer variable can only contain address of a variable of the same data type. In C language
address operator & is used to determine the address of a variable. The & (immediately
preceding a variable name) returns the address of the variable associated with it.
#include<stdio.h> void main()
{ int a =10; int *ptr;//pointer
declaration ptr =&a;//pointer
initialization

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;

ptr =&a;// ERROR, type mismatch

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.

#include <stdio.h> int


main() { int *ptr = NULL;
return0;

Notes Written By: Sanjay Kurmi (MCA), Digitalized By: Ashish Gupta
90

7.3 Describe the concept of Referencing and Dereferencing


Reference operator (&)
The reference operator noted by ampersand ("&"), is also a unary operator in c languages
that uses for assign address of the variables. It returns the pointer address of the variable.
This is called "referencing" operator.

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:

int c1; int*

p1; c1 =5; p1

=&c1;

//p1 references c1

Dereference operator (*)


The dereference operator or indirection operator, noted by asterisk ("*"), is also a unary
operator in c languages that uses for pointer variables. It operates on a pointer variable, and
returns l-value equivalent to the value at the pointer address. This is called "dereferencing"
the pointer.

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

You might also like