0% found this document useful (0 votes)
217 views206 pages

Computer Programming

This document provides an overview of a computer programming course for semester 3. It covers 9 units on topics like introduction to C programming language, operators and expressions, control statements, arrays, functions, pointers, structures, unions, and an introduction to C++ and object-oriented programming concepts. The document was originally created in 2013, and has since been revised multiple times, with the latest version from 2020. It contains a table of contents and learning objectives for each programming concept covered in the course.

Uploaded by

RahulChamp
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
217 views206 pages

Computer Programming

This document provides an overview of a computer programming course for semester 3. It covers 9 units on topics like introduction to C programming language, operators and expressions, control statements, arrays, functions, pointers, structures, unions, and an introduction to C++ and object-oriented programming concepts. The document was originally created in 2013, and has since been revised multiple times, with the latest version from 2020. It contains a table of contents and learning objectives for each programming concept covered in the course.

Uploaded by

RahulChamp
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 206

CP15

SEMESTER 3
COMPUTER
PROGRAMMING

SME:
SELVA JEEVITHA V A

Revised in 2013 by: Mr.VIJAY S SOUNDAR (DTC) & Mr. PRASANTH CHANDRAN P K (ONTC)
Prepared in 2020 by : Mrs.SELVA JEEVITHA VA (SNTC)
Modified in 2020 by: Mr.SHANKAR M G (Head E Learning)
Verified in 2020 by: Mr.SHANKAR M G (Head E Learning)
Approved in 2020 by: Mr.SHANKAR M G (Head E Learning)
Rev No : 04
Released Date : 01/07/2020
`

Table of Content

UNIT 1. INTRODUCTION TO COMPUTER PROGRAMMING .......................................................................... 3


1.1 COMPUTER PROGRAMMING ............................................................................................................ 3
1.2 HOW COMPUTER UNDERSTANDS OUR INSTRUCTIONS? ................................................................. 4
UNIT 2. INTRODUCTION TO C PROGRAMMING LANGUAGE........................................................................9
2.1 INTRODUCTION TO C PROGRAMMING LANGUAGE............................................................................ 9
2.2 C PROGRAM BUILDING AND ITS COMPARISON WITH ENGLISH LANGUAGE: ................................... 11
2.3 THE ‘C’ CHARACTER SET ..................................................................................................................... 11
2.4 TOKENS in C ....................................................................................................................................... 13
2.5 DATA TYPES, ENUMERATION & FORMAT SPECIFIERS ....................................................................... 19
2.6 VARIABLES AND STORAGE CLASSES. .................................................................................................. 23
2.7 HEADER FILES ..................................................................................................................................... 27
2.8 STRUCTURE OF C PROGRAM.............................................................................................................. 28
UNIT 3. OPERATORS AND EXPRESSIONS .................................................................................................... 33
3.1 ARITHMETIC, RELATIONAL AND LOGICAL OPERATORS ..................................................................... 33
3.2 BITWISE OPERATORS, INCREMENT AND DECREMENT OPERATORS.................................................. 37
3.3 ASSIGNMENT OPERATORS, SPECIAL OPERATORS, CONDITIONAL OPERATOR .................................. 43
3.4 HIERARCHY OF OPERATIONS ............................................................................................................. 45
3.5 DATATYPE CONVERSION AND MIXED MODE OPERATIONS .............................................................. 47
UNIT 4. CONTROL STATEMENTS ................................................................................................................ 54
4.1 FORMATTED INPUT/ OUTPUT FUNCTIONS........................................................................................ 55
4.2 UN - FORMATTED INPUT/ OUTPUT FUNCTIONS ............................................................................... 59
4.3 DECISION MAKING STATEMENT – IF …ELSE....................................................................................... 61
4.4 DECISION MAKING STATEMENT – SWITCH........................................................................................ 66
4.5 LOOPING STATEMENTS - FOR, WHILE, DO-WHILE............................................................................. 70
4.6 BREAK, CONTINUE, GOTO STATEMENTS ........................................................................................... 77
4.7 INFINITE LOOP.................................................................................................................................... 80
UNIT 5. ARRAYS ........................................................................................................................................... 86
5.1 SINGLE DIMENSIONAL ARRAY ............................................................................................................ 88
5.2 MULTI DIMENSIONAL ARRAY............................................................................................................. 91
5.3 STRINGS IN C ...................................................................................................................................... 94
UNIT 6. FUNCTIONS .................................................................................................................................... 98
6.1 FUNCTION - LIBRARY AND USER DEFINED FUNCTIONS, ELEMENTS OF FUNCTION .......................... 98
6.2 FOUR CATEGORIES OF FUNCTIONS ................................................................................................. 102
6.3 SCOPE OF VARIABLES - LOCAL AND GLOBAL VARIABLES................................................................. 106

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 1
`

6.4 RECURSION ...................................................................................................................................... 108


6.5 STRING FUNCTIONS ......................................................................................................................... 111
UNIT 7. POINTERS...................................................................................................................................... 115
7.1 POINTER - DECLARATION & DEFINITION……………............................................................................ 115
7.2 POINTER & ARRAYS .......................................................................................................................... 120
7.3 CALL BY VALUE & CALL BY REFERENCE ............................................................................................ 125
7.4 WRITING TO AND READING FROM FILE ........................................................................................... 130
7.5 C - PREPROCESSOR , MEMORY ALLOCATION IN C ...........................................................................138
UNIT 8. STRUCTURE AND UNION.............................................................................................................. 151
8.1 STRUCTURE - DECLARATION & ACCESSING STRUCTURE MEMBERS ............................................... 151
8.2 UNION - DECLARATION & ACCESSING UNION MEMBERS ............................................................... 159
Unit 9. C++ INTRODUCTION AND OOPS CONCEPTS ................................................................................. 165
9.1 OBJECT ORIENTED PROGRAMMING PARADIGM ............................................................................. 165
9.2 BENEFITS AND APPLICATIONS OF OOP ............................................................................................170
9.3 STRUCTURE OF C++ PROGRAM........................................................................................................ 171
9.4 SPECIFYING A CLASS: DATA MEMBERS & MEMBER FUNCTIONS, ACCESS SPECIFIERS .................... 173
9.5 OBJECT CREATION AND ITS MEMORY ALLOCATION........................................................................ 174
9.6 ACCESSING THE CLASS MEMBERS WITH OBJECTS........................................................................... 176
9.7 USING SCOPE RESOLUTION OPERATOR - MEMBER FUNCTION & DATA MEMBER ACCESS ............ 177
9.8 POLYMORPHISM, DYNAMIC BINDING, MESSAGE PASSING ............................................................ 180
9.9 CONSTRUCTOR & DESTRUCTOR ...................................................................................................... 183
9.10 SIMPLE INTRO - OPERATOR OVERLOADING & INHERITANCE CONCEPTS.......................................191

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 2
`

UNIT - 1
INTRODUCTION TO COMPUTER PROGRAMMING
1.1 COMPUTER PROGRAMMING
Computer programming is the process of developing and implementing various set of
instructions given to the computer to perform a certain predefined task. There are
many computer programming languages.

Language
English is one of the most popular and well-known Human Language. The English
language has its own set of grammar rules, which has to be followed to write in the
English language correctly.
Likewise, any other Human Languages (Hindi, kannada, Tamil, etc.) are made of several
elements like nouns, adjective, adverbs, propositions, and conjunctions, etc. So, just
like English, Hindi or other human languages, programming languages are also made of
different elements.

Programming Language
Just like human languages,
programming languages also
follow grammar called syntax.
There are certain basic program
code elements which are
common for all the programming
languages.

We write set of instruction for the computer to execute a given task, using predefined
language words in a logical sequence. The process writing these instructions in a logical
sequence is called computer programming.

These instructions written in a logical sequence is called as Coding.

One such programming language that gives instructions to the computer to do some
task is “C” Programming language. Computer Programming is easy if it is appropriately
managed.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 3
`

Most important basic elements for programming languages are:


 Programming Environment
 Data Types
 Variables
 Keywords
 Logical and Arithmetical Operators
 If else conditions
 Loops
 Numbers, Characters and Arrays
 Functions
 Input and Output Operations

1.2 HOW COMPUTER UNDERSTANDS OUR INSTRUCTIONS?


Imagine a situation in which an English speaking master calls, his Hindi speaking servant
and gives instructions to him, in Hindi to complete a task. Now this Hindi speaking
servant is unable to understand what his master is asking for. He remains in confused
state.

Let’s imagine the same situation, but with a translator present in between the master
and the servant. This translator is capable of translating English instructions in to Hindi.
Now the servant can understand the master’s command received through the
translator and completes the given task as the master wanted.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 4
`

Computer is an electronic machine. It has its own programming language called


Machine language. Any communication with computer must be in its machine
language. Computer interprets and executes a set of binary coded instructions called
machine language instructions.

Machine Language
Machine language consists of series of binary code patterns consisting 0's and 1's. So,
if we want to give instructions to a computer, it must be fed in the form of Machine
language. Example:
01010 => Load data into register.
01001 => Add the contents.
Practically, it is very difficult job to remember all these binary patterns representing
machine language.

Assembly Language
To make it easy to program, all machine codes are represented by mnemonic codes.
For example the mnemonic ADD is used to represent a binary operation code (machine
code) 01100 for an add operation.

Assembly language is designed to replace each and every binary machine code with an
easy understandable mnemonic code.

Assembly language is Machine-Dependent language and thus known as Low level


language.

High Level Language


It is comparatively easier to program using assembly language compared to using
machine language. But it is not user friendly. We need a language which resembles
with our spoken language. Thus ‘c’ language was designed to write programs for the
computers. Later c++, Java, FORTRAN, Pascal, Basic etc were designed. These are
called High Level Languages.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 5
`

The programs written in high level language are converted into machine language by
translators through a series of steps.

These translators are:


a. Assemblers.
b. Interpreters
c. Compiler.

HLL Program Translator Machine Language

C language uses compiler as a translator.


Compiler
A compiler is a computer program which transforms source code written in a high-level
language into low-level machine language. The compiler also makes the end code
efficient which is optimized for execution time and memory space. The compiling
process includes basic translation mechanisms and error detection.

Let us now look at how c language compiler works.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 6
`

FEW TOOLS THAT WORK WITH COMPILER:


a. Pre-processor: The pre-processor is
considered as a part of the Compiler. It is a
tool which produces input for Compiler. It
deals with macro processing,
augmentation, language extension, etc.
b. Assembler: It translates assembly language
code into machine understandable
language. The output result of assembler is
known as an object file which is a
combination of machine instruction as well
as the data required to store these
instructions in memory.
c. Linker: The linker helps you to link and
merge various object files to create an
executable file. All these files might have
been compiled with separate assemblers.
The main task of a linker is to search for called modules in a program and to find out
the memory location where all modules are stored.
d. Loader: The loader is a part of the OS, which performs the tasks of loading
executable files into memory and run them. It also calculates the size of a program
which creates additional memory space.

Watch & Learn : “Various Stages of program execution”


Click the following link or else just select the link, copy & paste the link in your browser
https://youtu.be/cJDRShqtTbk

Various Compilers of C Programming Language:


 Borland Turbo C
 GNU compiler collection
 Microsoft Visual C++
 Min GW Compiler
 Portable C Compiler (PCC)
 GCC Compiler
 CLANG

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 7
`

Time to recall

1. Explain what you understand by computer programming.


2. What do you understand by syntax of a programming language?
3. Why translators are required for high level languages?
4. Assemblers, Interpreters and Compilers are three types of translators. How
interpreters differ from compilers?
5. What type of translator does c language use?
6. Name any three programming languages.
7. Identify which of the following languages use interpretors and which use compilers.
C, Matlab, Perl, Pascal, Python, c++, Visual Basic
8. Which of the following programming languages uses compiler to get intermediate
form and then uses interpreter to get machine code?
Python, Java, Perl, c#

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 8
`

UNIT - 2
INTRODUCTION TO C PROGRAMMING LANGUAGE
Programming Languages are used to give instructions to the computer in order to do a
task. This we learnt in the previous unit. In this Unit we will study more about a
Computer programming language called “C”.

2.1 INTRODUCTION TO C PROGRAMMING LANGUAGE


C is a general-purpose high level language that was originally developed by Dennis
Ritchie for the Unix operating system. It was first implemented on the Digital
Equipment Corporation PDP-11 computer in 1972.
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 computers.

Facts about C
 C was invented to write an operating system called UNIX.
 C is a successor of B language which was introduced around 1970
 The language was formalized in 1988 by the American National Standard
Institute (ANSI).
 By 1973 UNIX OS almost totally written in C.
 Today C is the most widely used System Programming Language.
 Most of the state of the art software have been implemented using C

Where C programming is used? (Applications)


C was initially used for system development work, in particular the programs that
make-up the operating system. C was adopted as a system development language
because it produces code that runs nearly as fast as code written in assembly language.
Some examples of the use of C are:
 Operating Systems  Text Editors  Modern Programs
 Language Compilers  Print Spoolers  Data Bases
 Assemblers  Network Drivers  Language Interpreters

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 9
`

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

Machine Independent or Portable: Unlike


assembly language, c programs can be
complied for execution on different types of
operating systems with little or no change. C
is platform-dependent.

Mid-level programming language: C is also


used to do middle-level programming. It is
used to develop system utilities such as kernel (interacting with hardware), device
drivers etc. It can also be used to develop high level utilities and applications. That is
why it is known as mid-level language.

Structured programming language: C is a structured programming language in the


sense that we can organise the program using re-usable functions. So, it is easy to
understand and modify.

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

Memory Management: It supports the feature of dynamic memory allocation and de-
allocation. So pragrams can be written with less memory for data.

Speed: The compilation and execution time of C language is fast.

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

Recursion: In c, we can call the function within the same function.

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

Key Thought:
“Understand the features by their meaning. Once the entire C programming
topics are over, come back here and read once more the features of C. You would
understand better”

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 10
`

Watch & Learn : “Introduction – C Programming”


Click the following link or else just select the link, copy & paste the link in your browser
https://youtu.be/lJ4dRc_mn0w

2.2 C PROGRAM BUILDING AND ITS COMPARISON WITH ENGLISH


LANGUAGE:

Let us first know what alphabets, numbers and special symbols are used in C. We will
then learn how these are used to construct and define constants, variables, and
keywords. Finally learn how these are combined to form instructions. A group of
instructions are combined to form a program.

2.3 THE ‘C’ CHARACTER SET


Character: It denotes any alphabet, digit or special symbol used to represent
information.

Use of Character: Characters can be combined to form variables. C uses constants,


variables, operators, keywords and expressions as building blocks to form a basic C
program.

Character Set: The character set is the fundamental raw material for any language and
they are used to represent information. Similarly, computer language also have a well-
defined character set, which is useful write statements. These statements written in a
logical sequence will form a C program.
The characters in C are grouped into the following two categories:

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 11
`

a. Source character set


1. Alphabets
2. Digits
3. Special Characters
4. White Spaces
b. Execution character sets
Escape Sequences (Back slash characters)

Names Symbols
A, B, ….., Y, Z
Alphabets
a, b, ……, y, z
Digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
~‘!@#%^&*()_-+=|\{}
Special symbols
[]:;"'<>,.?/
White Spaces Tab Or New line Or Space

Meaningful Special Characters are listed below. Each of these characters have special
meaning in c language.
Symbol Name Symbol Name
~ Tilde – Minus sign
! Exclamation mark = Equal to sign
# Number sign { Left brace
% Percent sign } Right brace
^ Caret [ Left bracket
& Ampersand ] Right bracket
* Asterisk : Colon
( Left parenthesis ” Quotation mark
) Right parenthesis ; Semicolon
_ Underscore < Opening angle bracket
+ Plus sign > Closing angle bracket
| Vertical bar ? Question mark
\ Backslash , Comma
` Apostrophe . Period
$ Doller sign / Slash

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 12
`

Backslash Character Constants are as follows: These constants are used with backslash
character to give a special meaning.
Constant Meaning Constant Meaning
\a Audible Alert (Bell) \v Vertical Tab
\b Back Space \’ Single Quote
\f Form Feed \” Double Quote
\n New Line \? Question Mark
\r Carriage Return \\ Backslash
\t Horizontal Tab \0 Null

Watch & Learn : “Escape Sequences”


Click the following link or else just select the link, copy & paste the link in your browser
https://youtu.be/ULXZlskzR84

2.4 TOKENS in c
In C programs, each word and punctuation is referred to as a token. C Tokens are the
smallest building block or smallest unit of a C program. The compiler breaks
a program into the smallest possible units and proceeds to the various stages of the
compilation, which is called token.
We can say that C program is also a collection of tokens, comments, and whitespaces.
In C, Programming tokens are of six types. They are:

Keyword
Each keyword is meant to perform a specific function in a program.
a. Keywords are predefined reserved words whose meaning is special and it is already
described to the compiler
b. These meanings cannot be changed
c. They are fixed and cannot be used as identifiers (Variable names, function names,
structure names)
d. All keywords are written in lower case letters. (C is case sensitive)
e. There are 32 keywords in C
Keywords are written in lowercase letters.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 13
`

There are 63 keywords in C++. We will study these later.

Constants
The term constants refers to the fixed value. A Constant is that whose value is never
changed at the end of the program.
For example: 3x+2y=10

Here 3, 2 and 10 are constants. Their value never be change but here x and y are the
variables and may be they vary their value

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 14
`

a. Constants are also called as literals.


b. Constants are the memory locations in
which the values cannot be changed
during the execution of a program.
c. They are declared with the keyword
‘const’. (Declaration will be discussed in
the later parts of the subject)
d. There are 5 types of constants.

Constant Type of Value Stored


Integer Literals Literals which stores integer value. eg 8, 10, -40
Floating Literals Literals which stores decimal value. eg 9.56, 8.9909, -2.14
Character Literals Literals which stores character value. eg ‘A’, ‘B’, ‘a’, ‘1’, ‘%’
String Literals Literals which stores character array. eg. “My name”
Boolean Literals Literals which stores true or false value in terms of 1 and 0

All character constants are internally stored as integer values.There are 256 characters.

All alphabets, numbers, symbols, space are stored in the form of equivalent numbers
(values) internally by the computer. Since one byte (8 bits) is used for storing each
character, therefore computer supports 256 characters.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 15
`

Watch & Learn : “Constants In C”


Click the following link or else just select the link, copy & paste the link in your browser
https://youtu.be/KAvK4b_8POA

Identifiers
In C other programming languages, an identifier is a name that is assigned by the user
for a program element such as variable, type, template, function or namespace.

a. Identifiers are the names of variables, union, function name, structure names.
b. Identifier must follow some rules. Here are the rules:
 All identifiers can have letters (both uppercase and lowercase letters), digits and
underscore only.
 First character in a variable name must be an alphabet or an underscore Few
compilers allow currency character($)
 Commas, blanks or special symbols are not allowed within a variable name.
 After the first character, an identifier can have any combination of characters
(alphanumerical).
c. C keywords cannot be used as an identifier.
d. Identifiers in C are case sensitive, M2A and m2a are two different identifiers.
e. A variable name can be up to 8 characters in length, but some compilers allow
variable names up to 31 characters.
f. Two identifiers cannot have the same name.
g. It has to be declared before it is referred.
The following are the examples of legal identifiers:
MyVariable
myvariable
MYVARIABLE
x1
a
_myvariable
$myvariable
_9pins
nttf
NTtf
The following are not legal identifiers:
My Variable // Contains a space
9pins // Begins with a digit
a+c // The plus sign is not an alphanumeric character
testing1-2-3 // The hyphen is not an alphanumeric character

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 16
`

N'Ttf // Apostrophe is not an alphanumeric character


NTTF_&_Associates // ampersand (&) is not an alphanumeric character

String
a. A String is a collection of Characters. It is a sequence of characters terminated with
a null character \0.
b. Strings are always enclosed within double quotes.
c. When the compiler encounters a sequence of characters enclosed in the double
quotation marks, it appends a null character \0 at the end by default.
d. Example: “c string”.

Special Symbols
The following special symbols are used in C having some special meaning and thus,
cannot be used for some other purpose.
[] () {}, ; * = #
a. Brackets[]: Opening and closing brackets are used as array element reference. These
indicate single and multidimensional subscripts.
int name[30], marks[5];
b. Parentheses(): The parentheses are used to indicate function calls and function
parameters.
calculate( ); average( int a, int b) ;
c. Braces{}: These opening and ending curly braces mark the start and end of a block of
code containing more than one executable statement.
if (x==10){ ………
………
}
d. Semicolon (; ): It is used to separate each statement. In English we end each sentence
with full stop. In c the stements end with semicolon.
x = a + b;
for ( x=0; x<10; x++){
………..
………..
}
e. Comma (,): It is an operator that essentially invokes something called an initialization
list.
int x, mark, total;
f. Asterisk (*): It is used to create pointer variable.
int *b;
g. Assignment operator (=): It is used to assign values.
total = mark1 + mark2;

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 17
`

h. Preprocessor(#): The preprocessor is a macro processor that is used automatically


by the compiler to transform your program before actual compilation.
#include <stdio.h>
#define PI 3.14
Operators
Operators are symbols that triggers an action when applied to c variables. The data
items on which operators act upon are called operands.
Depending on the number of operands that an operator can act upon, operators can
be classified as follows:

These are of mainly 2 types: Unary & Binary Operators.

Unary Operators: These operators require only single operand to act upon.
Example increment and decrement operators.

Binary Operators: These operators require two operands to act upon.

Binary operators are classified into :


a. Arithmetic operators
b. Relational Operators
c. Logical Operators
d. Assignment Operators
e. Conditional Operators
f. Bitwise Operators

Ternary Operators: These operators requires three operands to act upon.


For Example Conditional operator(?:).

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 18
`

2.5 DATA TYPES, ENUMERATION & FORMAT SPECIFIERS

There are 3 different types of people shown above. If somebody asks them, to have
their seats, Where will these people locate themselves?. Obviously, the toddler shown
in the figure will occupy the yellow funny seat. The big family will place themselves
comfortable by sitting on the sofa. The young man would take the rolling chair.

Here, the small toddler can locate himself in all the seats, whereas, the big guys cannot
swap their positions to smaller seats. If they try so, some adverse situations arise. The
big family cannot locate themselves on the rolling chair or on the yellow funny seat.
Also, the young man can locate himself on the sofa, whereas he cannot be adjusted to
sit on the yellow funny seat.

In the same manner, whatever the data we are going to use in our C Program need to
be stored in some appropriate memory locations, based on their type and size. Data
we use can be numbers, floating point values, characters etc. Each data is of different
size. So, before we use in our program, they need to be recognised, which type they
belong to, and how much space is needed for them to get stored in the memory.

a. A data type is a special word used to allocate specific memory space for that data.
b. Data type represents the data in main memory (RAM) of the computer.
c. Data types represent the different values to be stored in the variable.
d. Every data type can have a range of values.
e. The compiler allocates memory space for each variable or constant according to its
data type.
f. Every variable in C has an associated data type.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 19
`

Primary data types


a. Integer Types
b. Floating-point Types
c. Character Types
Enumerated types
enum
Derived data types
a. Arrays
b. Pointer
c. Structure
d. Union
void
void
The primary data types
in C are:
int – Used to store integer numbers.
float – Used to store decimal values
(single precision floating point values).
double – Used to store decimal values
(double precision floating point values).
char – Used to store characters.
void – It is a null datatype.
(*The memory sizes in the below tables are mentioned as per the size allocated with Turbo C++
Compiler. To find the size of datatypes in other compilers use sizeof() operator*)
Watch & Learn : “sizeof() operator”
Click the following link or else just select the link, copy & paste the link in your browser
https://youtu.be/0rcx-fMi6Gw
Integer Data Type
Data Types Memory Size Range of values
Int 2 byte -32,768 to +32,767
signed int 2 byte -32,768 to +32,767
unsigned int 2 byte 0 to 65,535
short int 2 byte -32,768 to +32,767
signed short int 2 byte -32,768 to +32,767
unsigned short int 2 byte 0 to 65,535
long int 4 byte -2,147,483,648 to 2,147,483,647
signed long int 4 byte -2,147,483,648 to 2,147,483,647
unsigned long int 4 byte 0 to 4,294,967,295

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 20
`

Floating Point Data types


Type Storage size Value range Precision
float 4 byte 1.2E-38 to 3.4E+38 6 decimal places
double 8 byte 2.3E-308 to 1.7E+308 15 decimal places
long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal places

Character Data types


Data Types Memory Size Range
char 1 byte -128 to 127
signed char 1 byte -128 to 127
unsigned char 1 byte 0 to 255

Enumeration
Enumeration is a user defined datatype in C language. It is used to assign names to the
integral constants which makes a program easy to read and maintain. The keyword
“enum” is used to declare an enumeration.
Here is the syntax of enum in C language,
enum enum_name{const1, const2, ....... };
The enum keyword is also used to define the variables of enum type. There are two
ways to define the variables of enum type as follows.
enum week{sunday, monday, tuesday, wednesday, thursday, friday, saturday};
enum week day;

Here is an example of enum in C language,


#include<stdio.h>
enum week{Mon=10, Tue, Wed, Thur, Fri=10, Sat=16, Sun};
enum day{Mond, Tues, Wedn, Thurs, Frid=18, Satu=11, Sund};
int main()
{
printf("The value of enum week: %d\t%d\t%d\t%d\t%d\t%d\t%d\n\n",Mon , Tue,
Wed, Thur, Fri, Sat, Sun);
printf("The default value of enum day: %d\t%d\t%d\t%d\t%d\t%d\t%d",Mond , Tues,
Wedn, Thurs, Frid, Satu, Sund);
return 0;
}
Output:
The value of enum week: 10 11 12 13 10 16 17
The default value of enum day: 0 1 2 3 18 11 12

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 21
`

Watch & Learn : “Data Types”


Click the following link or else just select the link, copy & paste the link in your browser
https://youtu.be/Z91sIKxzG8M

FORMAT SPECIFIERS

a. Format specifiers can be defined as the operators which are used in association with
printf() function for printing the data that is referred by any object or any variable.
b. When a value is stored in a particular variable, then you cannot print the value
stored in the variable straightforwardly without using the format specifiers.
c. You can retrieve the data that are stored in the variables and can print them onto
the console screen by implementing these format specifiers in a printf() function.
d. Format specifiers start with a percentage % operator and followed by a special
character for identifying the type of the data.
There are mostly six types of format specifiers that are available in C.

Format specifier Description


%d Integer Format Specifier
%f Float Format Specifier
%c Character Format Specifier
%s String Format Specifier
%u Unsigned Integer Format Specifier
%ld Long Int Format Specifier

The % specifiers that you can use in C are:


Usual variable type Display
%c  char single character
%d (%i)  int signed integer
%e (%E)  float or double exponential format
%f  float or double signed decimal
%g (%G)  float or double use %f or %e as required
%o  int unsigned octal value
%p  pointer address stored in a pointer
%s  array of char sequence of characters
%u  int unsigned decimal
%x (%X)  int unsigned hex value

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 22
`

2.6 VARIABLES AND STORAGE CLASSES.


Variable is the name of the memory location where the values are stored. The value of
a variable changes during the execution of a program.
variable="vary + able" that means its value can be changed.

See the above figure. A box is named as M2 ’A’. In the beginning the Tanjore Doll is kept
inside the box. As time prolongs, we can replace this Tanjore Doll with any doll
according to our desire.

Imagine the same situation with variable. Variable is a memory location  like the box
mentioned above. Variable has a name  like the box named as M2 ‘A’. Variable can
store values  like the doll is kept inside the box. Variable values will be changing
during the execution of a program  like replacing the Tanjore doll with other dolls.

Do you remember?
Imagine the same example, The tanjore doll is kept inside the box named M2 ‘A’ and
the box is wrapped or sealed. Now, we cannot replace other dolls as we desire.
Roll back your memory to the topic “Constant” and compare its definition with the
above example. “Constant is a memory location, whose value cannot be changed
during the execution of a program”.

Rules for naming a Variable: We have seen earlier the naming rules for identifiers.
Variables are called identifiers.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 23
`

Declaration of a Variable

Declaration of a variable is telling the compiler about …..


- the data type of value (int, float, double or char) we are going to store in the
memory. (From the above example stated, memory  box, type of value  dolls).
- the name we are going to give to the memory location. (Name of the memory 
box name : M2 ‘A’).

Syntax: (Syntax is the rule how to use in the program)


datatype variablename;
datatype  int, float, char, double…. etc.,
Variable name  Name given to the memory location (Follow the rule
for naming the variable)

Example: int age;


Once the above statement is compiled, a memory location with the name ‘age’ will be
allotted with 2 bytes, for storing integers.

Note: We can declare more than one variable of same data type in a single line as
follows:
int marks, student_str, c; - int is only for integer numbers
float class_avg, e; - float is for decimal numbers

Initialisation of a Variable
Initialisation of a variable, is assigning values to the memory location.

Syntax:
datatype variablename = value; // initialisation along with declaration
(or)
datatype variablename;
variablename = value; // initialisation after declaration

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 24
`

int a = 10; - Value stored in a is 10


float c = 3.14, d = 5.99; - Value stored in c is 3.14 and in d is 5.99
(or)
int a; - Only declared, but no value assigned to a
float c, d; - Only declared, but no value assigned to c and d
a = 10; - 10 assigned to a
c=3.14; - 3.14 assigned to c

If no value is assigned then what content will be stored in that variable?

Watch & Learn : “Why do we need variable?”


Click the following link or else just select the link, copy & paste the link in your browser
https://youtu.be/zEhL5YOn1HU

Storage Class in ‘C’


a. From C compiler’s point of view, a variable name identifies some physical location
within the computer where the string (series) of bits representing the variable’s
value is stored.
b. There are basically two kinds of locations in a computer where such a value may be
kept in computer RAM or within CPU register(memory).
c. It is the variable’s storage class that determines in which of these two locations the
value is stored.
These are also called storage class specifiers
These specifiers tell the compiler how to store the subsequent variable. The general
form of a variable declaration that uses one is shown here:
storage_specifier datatype variablename;
Notice that the storage specifier precedes the rest of the variable declaration.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 25
`

A variable’s storage class tells us:


a. Where the variable would be stored.
b. What will be the initial value of the variable, if the initial value is not specifically
assigned. (i.e. the default initial value).
c. What is the scope of the variable; i.e. in which functions the value of the variable
would be available.
d. What is the life of the variable; i.e. how long would the variable exist.
There are four storage classes in C:
a. Automatic storage class
b. Register storage class
c. Static storage class
d. External storage class
Let us examine these storage classes one by one.
Automatic Storage Class
The features of a variable defined to have an automatic storage class are as under:

Features Description
Storage Memory (RAM)
Default initial value An unpredictable value, which is called a garbage value
Scope Local to the block in which the variable is defined
Life Till the control remains within the block in which the variable
is defined
Example: auto int a, marks;
Register Storage Class
The features of a variable defined to be of register storage class are as under:
Features Description
Storage CPU memory registers, faster access
Default initial value Garbage value
Scope Local to the block in which the variable is defined
Life Till the control remains within the block in which the variable is
defined
Example: register int a, marks;
Static Storage Class
The features of a variable defined to have a static storage class are as under:
Features Description
Storage Memory
Default initial value Zero
Scope Local to the block in which the variable is defined
Life Value of the variable persists between different function calls
Example: static int a, marks;

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 26
`

External Storage Class


Features Description
Storage Memory
Default initial value Zero
Scope Global scope
Life scope As long as the program’s execution doesn’t come to an end.
Example: extern int a, marks;

2.7 HEADER FILES


The basic C language provides only limited reserved words for programming. It has
many libraries consisting of predefined functions. These are included (#include
<stdio.h>) and used based on requirement. “stdio.h” is one such library file. C language
has provided input and output facility through this library (stdio.h) (standard input-
output). It is a header file. It has various functions which can be used by the
programmer. Similarly there are number fo header files.

a. Header files have the definitions of various functions and their associated variables
that needs to be included into your C program with the help of pre-processor
#include statement. (The pre-processor is a program invoked by the compiler that
modifies the source code before the actual composition takes place).
Example : #include <stdio.h>
#include <math.h>
b. All the header files have '.h' as its extension.

Some of the C header files are listed below:

Header file Declarations for


stdio.h Input/output functions
conio.h Console input/output functions
math.h Mathematical functions
string, h String manipulation functions
malloc.h Memory allocation/deallocation functions
stdlib. h Some standard library functions
ctype.h Character manipulation functions
time.h Time computing functions
graphics.h Graphical functions
dos.h Functions linking DOS routines
setjmp.h Jump functions
error.h Error handling functions
assert.h Diagnostic functions

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 27
`

Complete list of header files is as below:

2.8 STRUCTURE OF C PROGRAM


Any C program is consists of 6 main sections.

a. Documentation Section
b. Link Section
c. Definition Section
d. Global Declaration Section
e. main() Function Section
f. Subprogram Section

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 28
`

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 29
`

Explanation – Structure of a sample ‘c’ program – “HELLO HAPPY WORLD”


//Documentation Section:
// This program is to print hello happy world
/* Programmer Name: NTTF Trainee
Date of the Program: 22 / 03 / 2020
Semester: III Sem */
//Link Section:
#include<stdio.h>
//Definition Section:
#define HLO "Hello" // HLO is defined to contain “Hello”
//Global Declaration Section / Function Declaration Section:
char a[10]= “World” // this can also be written as a[10]= {‘W,’o’,’r’,’l’,’d’};
void display();
//Main Function Section :
void main()
{
char b[10]= {'H','a','p','p','y'}; // this can also be written as b[10]=”Happy”;
display(); // call display function
printf("%s %s %s \n", HLO, b, a);
getchar(); // wait for a character entry from keyboard
} //end of main function
//Sub Program Section:
void display()
{
printf("%s %s \n", HLO, a);
}
Note: Copy the complete code given above, compile and then execute.
Comments
Single line comment: Every thing written in that line after the symbol // will be taken
as comments.
Multi line Comment: Every thing written between /* and */ will be taken as comments.
All comments are neglected by the compiler. Comments are not part of program. They
are only to increase readability and documentation.
Documentation Section
This section consists of comment lines which include the name of the program, the
name of the programmer, the author and other details like time and date of writing the
program. Documentation section helps anyone to get an overview of the program. This
section will be skipped by the compiler.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 30
`

Link Section
The link section consists of the header files of the functions that are used in the
program. It provides instructions to the compiler to link functions from the system
library such as using the #include directive.
Definition Section
All the symbolic constants are written in the definition section.
Global Declaration / Function Declaration Section
The global variables that can be accessed anywhere in the program are declared in the
global declaration section. This section also declares the user defined functions.
Main Function Section
Every C program has one main() function. It is the beginning of every C program. It has
2 parts
Declaration part: The declaration part declares all the variables used in the executable
part.
Executable part: There is at least one statement in the executable part.
These two parts must appear between the opening and closing braces{ }. The program
execution begins at the opening brace and ends at the closing brace. The closing brace
of the main function is the logical end of the program. All statements in the declaration
and executable part end with a semicolon.
Sub Program Section

The subprogram section contains all the user defined functions that are used to
perform a specific task. These user defined functions are called in the main() function.
If the program is a multifunction program then the sub program section contains all the
user-defined functions that are called in the main () function. User-defined functions
are generally placed immediately after the main () function, although they may appear
in any order.

Watch & Learn : “Basic Structure of C ”


Click the following link or else just select the link, copy & paste the link in your browser
https://youtu.be/Jz0vvEd3Fr0

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 31
`

Time to recall

1. What is the difference between declaration and initialisation of a


variable?
2. Distinguish between about the scope of a variable Vs Life Time of a variable.
3. Can you create a header file of your own?
4. If a variable is not initialised with any value then what default value will be stored in
the variable? (Try a C Program with different storage classes and note down the
default values).
5. Which of the following are invalid variable names and why?
BASICSALARY break basic-hra
#MEAN group. main
population in 2006 over time mindovermatter
float hELLO queue.
team’svictory Plot # 3 2015_DDay
FLOAT 422 _basic
6. A variable name can have maximum of 31 characters. (Test your compiler, whether
it accepts more than 31 characters for variable name!)
7. How are constants declared in c language? What is their significance?
8. Differentiate variable and constant in C.
9. Link section has #include statements. What is the purpose of this statement?
10.#define HLO “Hello” What does this statement mean? What effect does it have
while compiling the program?
11.How many characters a variable can store?
a. 1 character b. 8 characters c. 254 characters d. Any number of
characters
12.How many bytes of memory will int data type require?
13.How many bytes of memory will float data type require?
14.How many bytes of memory will double data type require?
15. Every C programs will have atleast one function. Which function is that?

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 32
`

UNIT 3
OPERATORS AND EXPRESSIONS
C operators are symbols that are used to perform mathematical or logical
manipulations. The C programming language is rich with built-in operators.
3.1 to 3.3 Types of Operators:
a. Arithmetic Operators
b. Relational Operators
c. Logical Operators
d. Bitwise Operators
e. Increment and Decrement Operator
f. Assignment Operator
g. Special Operators
h. Conditional / Ternary Operator

3.1 ARITHMETIC, RELATIONAL AND LOGICAL OPERATORS


Arithmetic Operators
Arithmetic Operators are used to performing mathematical calculations like addition
(+), subtraction (-), multiplication (*), division (/) and modulus (%).

Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus (Remainder after division). Used only for int type data
In mathematical expression only () brackets can be used. The priority of calculation is:
Bracket -> Multiply and Divide -> addition and subtraction.
Example: 5 * 2 – 2 /2 = 9
5 * (2 - 2) / 2 = 0
(5 * (3 – 1)) / 2 = 5

Example: Program to perform arithmetic operations – Addition & Subtraction


#include<stdio.h>
void main()
{
int a=20, b=10, c;
c=a + b;
printf("\nThe sum of %d and %d is %d",a, b, c);
c = a - b;
printf("\nThe difference between %d and %d is %d",a, b, c);

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 33
`

printf("\n 5 * 2 – 2 / 2=%d",5*2-2/2);
printf("\n 5 * ( 2 - 2 ) / 2=%d",5*(2-2)/2);
printf("\n (5 *( 3 – 1 ) / 2 )=%d",(5*(3-1)/2));
getchar(); // wait for a key press
} // end of main function
Output:
The sum of 20 and 10 is 30
The difference between 20 and 10 is 10
5 * 2 – 2 /2 = 9
5 * (2 - 2) / 2 = 0
(5 * (3 – 1)) / 2 = 5

#include<stdio.h>
void main()
{
int a = 25, b = 4, c;
float d=25, e = 4, f;
c = a/b;
printf("\nc is integer = %d",c);
f = d/e;
printf("\n f is float = %f", f);
printf("\n a%b =%d", a%b);
getchar(); // wait for a key press
} // end of main function
Output:
c is integer = 6
f is float = 6.25
a%b =1
Watch & Learn : “Arithmetic Operators”
Click the following link or else just select the link, copy & paste the link in your browser
https://youtu.be/SY9OTe-0k8w

Relational Operators
Relational operators are used to comparing two quantities or values. These are used
with the if condition evaluator. The logic is :
if (condition true)
{
Execute statements in this block
}
else // if not true
{
Execute statements in this block
}

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 34
`

Operator Description
== Is equal to
!= Is not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to

Example: Program to compare two values


#include<stdio.h>
void main()
{
int a = 20, b = 10;
if(a > b)
{
printf("\n %d is greater",a);
}
else
{
printf("\n %d is greater",b);
}
getchar();
} // end of main function
Output:
20 is greater

Put different values for a and b and try out.

Watch & Learn : “Relational Operators in C”


Click the following link or else just select the link, copy & paste the link in your browser
https://youtu.be/IVb3EwXo5N8

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 35
`

Logical Operators
C provides three logical operators when we test more than one condition to make
decisions. These are: && (meaning logical AND), || (meaning logical OR) and ! (meaning
logical NOT).

Operator Description
And operator. It performs logical conjunction of two expressions. (if both
&& expressions evaluate to True, result is True. If either expression
evaluates to False, the result is False)
Or operator. It performs a logical disjunction on two expressions. (if
||
either or both expressions evaluate to True, the result is True)
! Not operator. It performs logical negation on an expression.

Example: Program to compare three values


#include<stdio.h>
void main()
{
int a=10, b=10,c=0;

if(a==b && a==c) //if (a equals b and also a equals c)


{
printf("a, b and c are equal");
}
else if ((a==b) || (a==c)) // if (a equals b or a equals c)
{
printf("Two of them are equal");
}
else // above conditions are false
{
printf("all are different");
} // end of if
getchar();
}
We can also put if inside another if
Example
#include<stdio.h>
void main()
{
int a=10,b=30,c=5;

if( ! (a==b && a==c)) //if NOT (a equals b and a equals c)


{

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 36
`

if(a>b && a>c) // is a greater than b and c


{
printf("\n %d is greater",a);
}
else
if(b>c) // is b greater than c
{
printf("\n %d is greater",b);
}
else
{
printf("\n %d is greater",c);
}
}
else
{
printf("all the values are equal");
}
getchar();
}
Output:
30 is greater
Modify the above program to clearly understand where if- else if- start and end.

Watch & Learn : “Logical Operators in C”


Click the following link or else just select the link, copy & paste the link in your browser
https://youtu.be/o3rd_RMD7Ss

3.2 BITWISE OPERATORS, INCREMENT AND DECREMENT OPERATORS


Bitwise Operators
The data is always stored in computer in the form of bytes (8 bits). C provides a special
operator for bit operation between two variables.
In arithmetic-logic unit (which is inside the CPU), mathematical operations like:
addition, subtraction, multiplication and division are done at bit-level. To perform bit-
level operations in C programming, bitwise operators are used.

Note: && and || are used for logical testing. The output is True or False

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 37
`

Operator Description
& Bitwise AND Operator
| Bitwise OR Operator
~ Bitwise Ones Complement Operator
^ Bitwise XOR Operator
<< Bitwise Left Shift Operator
>> Bitwise Right Shift Operator

Know More about bitwise operators…. which is ignored mostly!


This operator is very useful in embedded systems, where each bit represents a data,
such position of a switch.

Bitwise AND operator


The output of bitwise AND is 1 if the corresponding bits of two operands is 1. If either
bit of an operand is 0, the result of corresponding bit is evaluated to 0.

Let us suppose the bitwise AND operation of two integers 12 and 25.
28 = 00011100 (In Binary)
25 = 00011001 (In Binary)
Bit Operation of 28 and 25
00011100
& 00011001
--------------
00011000 = 24 (In decimal)
Example:
#include <stdio.h>
void main()
{
int a = 28, b = 25;
printf("Output = %d", a&b);
getchar();
}
Output:
Output = 24

Watch & Learn : “Bitwise AND Operator”


Click the following link or else just select the link, copy & paste the link in your browser
https://youtu.be/OFzbCdCwPH8

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 38
`

Bitwise OR operator
The output of bitwise OR is 1 if at least one corresponding bit of two operands is 1. In
C Programming, bitwise OR operator is denoted by |.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)

Bitwise OR Operation of 12 and 25


00001100
| 00011001
-------------
00011101 = 29 (In decimal)
Example:
#include <stdio.h>
void main()
{
int a = 12, b = 25;
printf("Output = %d", a|b);
getchar();
}
Output:
Output = 29

Watch & Learn : “Bitwise OR Operator”


Click the following link or else just select the link, copy & paste the link in your browser
https://youtu.be/9qYD12jws8g

Bitwise one’s Complement operator


Bitwise compliment operator is an unary operator (works on only one operand). It
changes 1 to 0 and 0 to 1. It is denoted by ~.
35 = 00100011 (In Binary)
Bitwise complement Operation of 35
~ 00100011
-------------
11011100 = 220 (in decimal)
Twist in bitwise complement operator in C Programming
The bitwise complement of 35 (~35) is -36 instead of 220, but why?
In computer complement of n = ~n = -(n+1).
To understand this, you should have the knowledge of 2's complement.
2's Complement
Two's complement is an operation on binary numbers.
The 2's complement of a number is equal to the complement of that number plus 1.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 39
`

For example:
Decimal Binary 2's complement
0 00000000 -(11111111+1) = -00000000 = -0(decimal)
1 00000001 -(11111110+1) = -11111111 = -256(decimal)
12 00001100 -(11110011+1) = -11110100 = -244(decimal)
220 11011100 -00100011+1) = -00100100 = -36(decimal)

Note: Overflow is ignored while computing 2's complement.


The bitwise complement of 35 is 220 (in decimal).
The 2's complement of 220 is -36.
Hence, the output is -36 instead of 220.
Bitwise complement of any number N is -(N+1).
Here's how: bitwise complement of N = ~N (represented in 2's complement form)
2'complement of ~N= -(~(~N)+1) = -(N+1)
Example:
#include <stdio.h>
void main()
{
printf("Output = %d\n",~35);
printf("Output = %d\n",~ -12);
getchar();
}
Output:
Output = -36
Output = 11

Bitwise XOR operator


The result of bitwise XOR operator is 1 if the corresponding bits of two operands are
opposite. It is denoted by ^.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bitwise XOR Operation of 12 and 25
00001100
^ 00011001
---------------
00010101 = 21 (In decimal)
Example:
#include <stdio.h>
void main()
{
int a = 12, b = 25;

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 40
`

printf("Output = %d", a^b);


getchar();
}
Output:
Output = 21

Bitwise Right & Left Shift Operators

Right Shift Operator

Right shift operator shifts all bits towards right by certain number of specified bits. It is
denoted by >>.
212 = 11010100 (In binary)
212>>2 = 00110101 (In binary) [Right shift by two bits]
212>>7 = 00000001 (In binary) Right shift by 7 bits
212>>8 = 00000000
212>>0 = 11010100 (No Shift)

Left Shift Operator


Left shift operator shifts all bits towards left by certain number of specified bits. It is
denoted by <<.
212 = 11010100 (In binary)
212<<1 = 110101000 (In binary) [Left shift by one bit]
212<<0 =11010100 (Shift by 0)
212<<4 = 110101000000 (In binary) =3392(In decimal)

Example:
#include <stdio.h>
void main()
{
int num=212;
printf("Right shift by 1: %d\n", num>>1);
printf("Left shift by 2: %d\n", num<<2);
getchar();
}
Output:
Right Shift by 1: 106
Left Shift by 2: 848

Watch & Learn : “Bitwise Left Shift & Right Shift Operator”
Click the following links or else just select the links, copy & paste the links in your browser
https://youtu.be/sUMLLAoI8Kw
https://youtu.be/y2tUNlnS1fc
Increment And Decrement Operators

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 41
`

Increment and Decrement Operators are useful operators generally used to minimize
the calculations, i.e.
++x and x++ => x = x + 1
--x and x−− => x = x - 1.
But there is a slight difference between ++ or −− written before or after the operand.
Applying the pre-increment(++x), first do increment and then use the result.
Post-increment(x++), use the value and then do the increment.
Operator Description
++ Increment
−− Decrement
Example: To Demonstrate prefix and postfix modes.
#include <stdio.h>
void main()
{
int a=5, b=5;
printf("\n%d %d",a--,--b); // Print a and then decrement
printf("\n%d %d",a--,--b); // Decrement b and then print
printf("\n%d %d",a--,--b);
printf("\n%d %d",a--,--b);
printf("\n%d %d",a--,--b);
getchar();
}
Output:
54
43
32
21
10

Watch & Learn : “Increment & Decrement Operator”


Click the following link or else just select the link, copy & paste the link in your browser
https://youtu.be/kxT0tvdAkrg

3.3 ASSIGNMENT OPERATORS, SPECIAL OPERATORS, CONDITIONAL


OPERATOR
Assignment Operators

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 42
`

Assignment operators applied to assign the result of an expression to a variable. C has


a collection of shorthand assignment operators.
Operator Description
= Assign
+= Add then assign a+=b => a = a + b
-= Subtract then assign a-=b => a = a – b
*= Multiplies then assign a*=b => a = a * b
/= Divides then assign a/=b => a = a / b
%= Modulus then assign a%=b => a = a % b
<<= Left shift and assign a<<=2 => a = a <<2
>>= Right shift and assign a>>=2 => a = a >>2
&= Bitwise AND , then assign a&=b => a = a & b
^= Bitwise exclusive OR and assign a^=b => a = a + b
|= Bitwise inclusive OR and assign a|=b => a = a | b
Example:
#include <stdio.h>
void main()
{
int a=5, b=5;
a+=b; // this statement is equivalent to a=a+b
printf("\n%d",a);
a-=b; // this statement is equivalent to a=a-b
printf("\n%d",a);
a*=b; // this statement is equivalent to a=a*b
printf("\n%d",a);
getchar();
}
Output:

10
5
25

Watch & Learn : “Assignment Operator”


Click the following link or else just select the link, copy & paste the link in your browser
https://youtu.be/Xdiqd1SpXiw

Special Operators

C supports some special operators


Operator Description

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 43
`

sizeof() Returns the size of a memory location.


& Returns the address of a memory location.
* Pointer to a variable.
Here &, * are used as unary operators. We will learn more about them when we study
Pointers.
Example:
#include <stdio.h>
void main()
{
int i=10;
printf("integer: %d\n", sizeof(i));
getchar();
}
Output:
2
Modify the program an d cerify the sizeof float, char and double

Conditional Operator
C offers a ternary operator which is the conditional operator to construct conditional
expressions.
?: is the conditional operator
Syntax:
ConditionExpression ? True statement or value : False statement or value;
The above syntax can be interpreted as follows:
Example:
#include <stdio.h>
void main()
{
int a=30,b=20,c;
c=a>b?a:b;
printf("The greatest value is: %d\n",c);
printf("Conditional answer: %d\n", (a==b)? a + b: a - b);
getchar();
}
Output:
The greatest value is: 20
Conditional answer: 10
Watch & Learn : “Ternary Operator”
Click the following link or else just select the link, copy & paste the link in your browser
https://youtu.be/At5aVksyCCU

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 44
`

3.4 HIERARCHY OF OPERATIONS


When more than one arithmetic operator appears in an arithmetic expression then it
is important to note which operator is evaluated first, which is operated second and
which operator has the last priority. The order in which the arithmetic operators are
executed is called the hierarchy of operations.
C operators in order of precedence (highest to lowest). Their associatively indicates in what order
operators of equal precedence in an expression are applied.
Operator Description Associativity
() Parentheses (function call) (see Note 1)
[] Brackets (array subscript)
. Member selection via object name
-> Member selection via pointer left-to-right
++ -- Postfix increment/decrement (see Note 2)
++ -- Prefix increment/decrement
+- Unary plus/minus
!~ Logical negation/bitwise complement
(type) Cast (convert value to temporary value of type)
* Dereference right-to-left
& Address (of operand)
sizeof Determine size in bytes on this implementation
* / % Multiplication/division/modulus left-to-right
+ - Addition/subtraction left-to-right
<< >> Bitwise shift left, Bitwise shift right left-to-right
< <= Relational less than/less than or equal to
> >= Relational greater than/greater than or equal to left-to-right
== != Relational is equal to/is not equal to left-to-right
& Bitwise AND left-to-right
^ Bitwise exclusive OR left-to-right
| Bitwise inclusive OR left-to-right
&& Logical AND left-to-right
|| Logical OR left-to-right
?: Ternary conditional right-to-left
= Assignment
+= -= Addition/subtraction assignment
*= /= Multiplication/division assignment
%= &= Modulus/bitwise AND assignment right-to-left
^= |= Bitwise exclusive/inclusive OR assignment
<<= >>= Bitwise shift left/right assignment
, Comma (separate expressions) left-to-right
Note 1: Parentheses are also used to group sub-expressions to force a different precedence; such
parenthetical expressions can be nested and are evaluated from inner to outer.

Note 2: Postfix increment/decrement have high precedence, but the actual increment or
decrement of the operand is delayed (to be accomplished sometime before the statement
completes execution). So in the statement y = x * z++; the current value of z is used to evaluate the
expression (i.e., z++ evaluates to z) and z only incremented after all else is done.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 45
`

For Example: Arithmetic expression a - b / c * d is equivalent to a - (b/c) * d because


‘/’ has higher precedence.
The natural order of evaluation can be altered, through the use of parentheses
(highest precedence). If the given arithmetic expression has many pairs of
parentheses then the contents of inner most parentheses is evaluated first, the next
innermost pair is evaluated as second step and so on to the outer most parentheses.

For example: (a - b) / (c*d) expression gives a different result compared to the above
expression.
Example:
Determine the hierarchy of operations and evaluate the following
k=3/2*4+3/8+3
Stepwise evaluation of this expression is shown below:
k=3/2*4+3/8+3
k=1*4+3/8+3 operation 1: 3/2 (from left to right)
k=4+3/8+3 operation 2: 1*4 (from left to right)
k=4+0+3 operation 3: 3/8 (from left to right)
k=4+3 operation 4: 4+0 (from left to right)
k=7 operation 5: 4+3

Note: The result of 3/2 = 1, 3/8 = 0 because these numbers have been used as
integers.
#include <stdio.h>
int main()
{
int k1_int;
float k_float;
k1_int = 5 / 3 * 4 + 3 / 8 + 3;
printf("\n 5 / 3 * 4 + 3 / 8 + 3 = %d", k1_int);
k_float = 5 / 3 * 4 + 3 / 8 + 3;
printf("\n 5 / 3 * 4 + 3 / 8 + 3 = %f", k_float);
k_float = 5.0 / 3 * 4 + 3 / 8 + 3;
printf("\n 5.0 / 3 * 4 + 3 / 8 + 3 = %f", k_float);
k_float = 5.0 / 3 * 4 + 3.0 / 8 + 3;
printf("\n 5.0 / 3 * 4 + 3.0 / 8 + 3 = %f", k_float);
getchar();
return 0;
}

Output:
5/2*4+3/8+3=7
5 / 2 * 4 + 3 / 8 + 3 = 7.000000
5.0 / 3 * 4 + 3 / 8 + 3 = 9.666667
5.0 / 3 * 4 + 3.0 / 8 + 3 = 10.041667

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 46
`

Answers are different because:


In integers 5/2 = 2
Where as 5.0/2 = 2.5. Because 5.0 is taken as decimal number.
a. In 5 / 2 * 4 + 3 / 8 + 3 all numbers are taken as integers.
b. In 5.0 / 3 * 4 + 3 / 8 + 3 => 5.0 is taken as decimal number
c. In 5.0 / 3 * 4 + 3.0 / 8 + 3 => 5.0 and 3.0 are taken as decimal numbers.
These aspects are explained in the next section.
Watch & Learn : “Operator Precedence in C”
Click the following link or else just select the link, copy & paste the link in your browser
https://youtu.be/t1_MK1Rc67g

3.5 DATATYPE CONVERSION AND MIXED MODE OPERATIONS


C permits mixing of constants and variables of different types in an expression. In these
types of operations, data type of one operand is converted into data type of another
operand to get a uniform type. This is known as type conversion.
There are two types of type conversion:
a. Implicit type conversion.
b. Explicit type conversion.
Implicit type conversions are done by the compiler while the explicit type conversions
are user defined conversions.
Implicit type conversions

When one data type is converted to another data type, automatically by the compiler,
then it is called as Implicit Conversion. This type of conversion usually occurs when
there is a mixed mode of operation, ie, more than one data type elements involved in
an expression.
For Example, assume in our program, we have the following elements/ data.
int i = 90;
float f = 3.5;
char c = ’A’;
double d = 2.3456;
double result = (f*i) + (i/c) - (d*i);
Now, we’ll examine the expression (f*i) + (i/c) - (d*i) and its assignment to the variable
result.
Step 1: (f * i), where, f is float and i is an integer. This is a mixed mode operation. Now,
the lower data type ‘integer’ will be converted to the higher data type ‘float’,
automatically by the compiler.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 47
`

Therefore, i will be converted to float data type by the compiler and is multiplied with
the value of f. The resultant value will be float.
(f*i)  3.5*90 3.5*90.0 315.000000

Step 2: (i / c) where, i is an integer and c is char. This is a mixed mode operation. Now,
the lower data type ‘char’ will be converted to the higher data type ‘int’, automatically
by the compiler.
Therefore, c will be converted to int data type by the compiler and is divided with the
value of i. The resultant value will be int.

(i/c)  90*’A’ 90/651 (ASCII CODE of ‘A’ is 65)

Step 3: (d * i) where, d is double and i is integer. This is a mixed mode operation. Now,
the lower data type ‘integer’ will be converted to the higher data type ‘double’,
automatically by the compiler.
Therefore, i will be converted to double data type by the compiler and is multiplied
with the value of d. The resultant value will be double.

(d*i)  2.3456*90 2.3456*90.000211.104000

Step 4: (f + i)  float is added with (i/c)  integer. So, the resultant value is obviously
float value. This float value is subtracted with (d * i)  double. So, the resultant will be
a double value.
315.000000+1  315.000000+1.000000 316.000000
316.000000- 211.104000 104.896000

(The following program is run under Turbo C++ environment)

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 48
`

Output:

All the above-mentioned rules can be simplified by assigning a rank to each data type.
When the expression contains different types of data items, the operand with a lower
rank will be converted to the type of higher rank operand. This is called promotion of
data type.
___________________________________________________________________

Type Conversion in Assignment


If the types of the two operands in an assignment expression are different, then the
type of the right hand side operand is converted to the type of left hand operand
according to the following rules.
Rule 1: If the right hand operand is of lower rank then it will be promoted to the rank
of left hand operand.
For example,
float b;
b = 30;
Here right operand 30 is of type int and the left-hand operand is of type float. According
to rule lower rank operand (in this case int) will be promoted to a higher rank (in this
case float). So before assignment 30 will be promoted to float and then assigned to b.
Hence what gets stored in b is 30.000000.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 49
`

Rule 2: If right-hand operand is of higher rank then


it will be demoted to the rank of left-hand operand.
For Example:
int i;
i = 3.5;
Here right operand 3.5 is of type float and the
left-hand operand is of type int. According to rule
higher rank operand (in this case float) will be
demoted to the lower rank (in this case int). So
before assignment 3.5 will be demoted to int and
then assigned to i. Hence what gets stored in i is 3.

Some consequences of these promotions and


demotions are:
a. Some high order bits may be dropped when long
int is converted to int, or int is converted to short
int or char.
b. Fractional part will be truncated during
conversion of float type to int type.
c. When double type is converted to float type,
digits are rounded off.
d. When a signed type is changed to unsigned type,
the sign may be dropped.
e. When an int is converted to float,
or float to double there will be no increase in
accuracy or precision.
Example:
#include <stdio.h>
void main()
{
char ch1, ch2;
int i1, i2;
float f1, f2;
ch1 = 'A';
/* float is demoted to int, only 70 is assigned to i1 */
i1 = 70.56;
f1 = 10.6;
/* int is demoted to char, ch2 = 70 =’F’ in ASCII */
ch2 = i1;
/* float is demoted to int, only 10 is assigned to i2 */
i2 = f1;
/* Now ch2 has the character with ASCII value 70, i2 is assigned value 10. */
printf("ch2 = %c \n", ch2);

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 50
`

printf("i2 = %d \n\n", i2);


/* int is promoted to float */
f2 = i1;
/* char is promoted to int */
i2 = ch1;
/* Now i2 contains ASCII value of character 'A' which is 65 */
printf("f2 = %.2f \n", f2);
printf("i2 = %d \n", i2);
getchar();
}
Output:
ch2 = F
i2 = 10
f2 = 70.00
i2 = 65

Explicit type conversions: (Otherwise known as Type Casting)


We have just discussed how C performs type conversion automatically. However, it is
always good idea to force a type conversion in a way that is different from the
automatic conversion. For example:
float z;
int x = 40, y = 3;
z = x/y;
The value of z will be 13.000000 instead of 13.333333 because operation between two
integers yields an integer value. In these types of cases we can specify our own
conversions known as type casting. This is done with the help of type cast operator. The
type cast operator is a unary operator that is used for converting an expression to a
particular data type temporarily.
The syntax of cast operator is:
(datatype)expression
Here the datatype along with the parentheses is called the type cast operator.
If we write the above statement as:
z = (float)x/y;
The value of z will come out to be 13.333333. This happens because the type cast
operator (float) temporarily converted the int variable x into float type and so mixed
mode arithmetic took place and fractional part was not lost.

Note: The type cast operator changes the data type of variable x only temporarily for
the evaluation of this expression, everywhere else in the program it will be
an int variable only.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 51
`

The following program demonstrates this example.


#include <stdio.h>
void main()
{
float z, r;
int x = 40, y = 3;
z = x / y;
printf("z = %f\n", z);
r = (float)x / y;
printf("r = %f", r);
getchar();
}
Output:
z = 13.000000
r = 13.333333

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 52
`

Time to recall & Test yourself!


1. Evaluate the following expressions and show their hierarchy.
(a) g = b / 2 + b * 4 / b - b + a / 3 ;
(a = 2.5, b = 2, assume g to be a float)
(b) x = i * a / 2 + 3 / 2 * a + 2 + t ;
(i = 4, a = 1, t = 3.2, assume x to be an int)
(c) s = q * a / 4 - 6 / 2 + 2 / 3 * 6 / g ;
(q = 4, a = 2, g = 2, assume s to be an int)
(d) r = 1 / 3 * a / 4 - 6 / 2 + 2 / 3 * 6 / b ;
(a = 4, b = 3, assume r to be an int)
2. Convert the following equations into corresponding C statements.

3. Which of the following statement is wrong


(a) mes = 123.56 ; (b) con = 'T' * 'A' ;
(c) this = 'T' * 20 ; (d) 3 + a = b ;
4. If a is an integer variable, a = 5 / 2 ; will return a value
(a) 2.5 (b) 3 (c) 2 (d) 0
5. What will be the value of d if d is a float after the operation d = 2 / 7.0?
(a) 0 (b) 0.2857 (c) Cannot be determined (d) infinity
6. In C, Arithmetic instruction/expression cannot contain
(a) variables (b) constants
(c) variable names on right side of = (d) constants on left side of =
7. What is the result of the statement - printf(“%d”, 13%4);
8. What is hierarchy of operators?
9. x = (10 > 15)? 1 : 0; What is stored in x?
10. x = sizeof (char); What is stored in x?
11. x =10; y = 5 + ++x; What is stored in y?
12. x =10; y = 5 + x++; What is stored in y?
13. x=10; y = 7; a = x && 0; b = x && 1; k = x & y; What values are stored in a, b and k?
14. x =10; x % = 6; What is stored in y?
15. What symbol is used to end every statement in ‘C’ program?

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 53
`

UNIT - 4
CONTROL STATEMENTS
Before we move in depth into the control statements, let us begin this unit, with Input
and Output functions of C.
Input Output Functions
The developers of C compilers wrote several standard I/O functions and put them in
libraries. These libraries are available with all C compilers. Whichever C compiler you
are using it’s almost certain that you have access to a library of I/O functions. (header
files)
I/O facilities for different operating systems would be different. The way one OS
displays output on screen may be different than the way another OS does it.
There are many library functions available for Input Output operations. They are
broadly classified as follows:
a. Console IO functions - Functions to receive input from keyboard and write output
to VDU. (Visual Display Unit)
b. File IO functions - Functions to perform I/O operations on a hard disk or other
external storage. (This will be discussed in Unit 7  Chapter 7.4)

Console IO Functions:
The screen and keyboard together are called a console. Console I/O functions can be
further classified into two categories—formatted and unformatted console I/O
functions.

Console I/O Functions

Formatted I/O functions Un-Formatted I/O funtions

The basic difference between them is that the formatted functions allow the input read
from the keyboard or the output displayed on the VDU to be formatted as per our
requirements.
For example, if values of average marks or percentage marks are to be displayed on the
screen, then the details like where this output should appear on the screen, number of
spaces between the two values, the number of places after the decimal point, etc. can
be controlled using formatted functions.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 54
`

4.1 FORMATTED INPUT/ OUTPUT FUNCTIONS


Formatted Console – Output Function: printf()
The general syntax of it:
printf ( "format string", list of variables ) ;

The format string can contain:


a. Characters that are simply printed
as they are
b. Conversion specifications or
format specifications that begin
with a % sign
c. Escape sequences (Backslash
characters) that begin with a \
sign
For example,
#include <stdio.h>
void main()
{
int ave = 346;
float per=69.2;
printf(“AVERAGE = %d \n PERCENTAGE = %f”,ave,per);
getchar();
}
Output:
AVERAGE = 346
PERCENTAGE = 69.200000

Interpretation of the printf() statement:


The printf() statement, examines the format string from left to right. So long as it
doesn’t come across either a % or a \ it continues to dump the characters that it
encounters, on to the screen.

In this example Average = is dumped on the screen. The moment it comes across a
conversion specification in the format string it picks up the first variable in the list of
variables and prints its value in the specified format.

In this example, the moment %d is picked, the variable avg is picked up and its value is
printed. Similarly, when an escape sequence is picked, it takes the appropriate action.
In this example, the moment \n (new line) is picked it places the cursor at the beginning
of the next line. This process continues till the end of format string is not reached.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 55
`

 Format Specifications
The %d and %f used in the printf( ) are called format specifiers. They tell printf( ) to
print the value of avg as a decimal integer and the value of per as a float.
The various format specifiers were discussed in the Unit 2  Chapter 2.5.
To have a quick look, refer the following table:

We can also provide optional specifiers in the format specification:

dd - Digits specifying the field width & - Minus sign for left justification:
We’ll execute the following program in the Turbo C++ compiler and see the output.
void main()
{
int w=65;
printf(“%d”,w);
printf(“\n%4d”,w); // field width of 4 and right justified
printf(“\n%6d”,w); // field width of 6 and right justified
printf(“\n%-6d”,w); // field width of and left justified
getchar();
}

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 56
`

The output as follows:

To interpret this output, the following table is framed. Consider the table as the output
console window. Each column specifies each character space.
Field Width 
1 2 3 4 5 6 7 8
6 5
6 5
6 5
6 5

. – Decimal point separating the field width from precision & dd – Digits specifying
the precision.
We’ll execute the following program in the Turbo C++ compiler and see the output.
void main()
{
float w=65.55;
printf(“%f”,w);
printf(“\n%10.3f”,w); // field width of 10,right justified, 3 digits after decimal.
printf(“\n%-10.3f”,w); // field width of 10,left justified, 3 digits after decimal.
getchar();
}
The output as follows:

To interpret this output, the following table is framed. Consider the table as the output
console window. Each column specifies each character space.
Field Width 
1 2 3 4 5 6 7 8 9 10
6 5 . 5 5 0 0 0 3
6 5 . 5 5 0
6 5 . 5 5 0

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 57
`

 Escape Sequences (Backslash characters) (already dealt in Unit 2  2.3)

To have a quick look about Escape sequence, the following table would explain that in
detail.

In a printf() statement, we use these escape sequences for the about said purposes to
be effected on the output screen.
Example: printf(“Hello \n NTTF”);
The output will introduce a new line between Hello and NTTF.

Output:
Hello
NTTF

Watch & Learn : “Printf Function In C”


Click the following link or else just select the link, copy & paste the link in your browser
https://youtu.be/53UzOVLWXsc

Formatted Console – Input Function: scanf()


The general form of scanf( ) statement is as follows:
scanf ( "format string", list of addresses of variables ) ;
For example:
scanf ( "%d %f %c", &c, &a, &ch ) ;
Note that we are sending addresses of variables (addresses are obtained by using ‘&’
the ‘address of’ operator) to scanf( ) function. This is necessary because the values
received from keyboard must be dropped into variables corresponding to these
addresses. The values that are supplied through the keyboard must be separated by
either blank(s), tab(s), or newline(s). Do not include these escape sequences in the
format string.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 58
`

All the format specifications that we learnt in printf( ) function are applicable to scanf(
) function as well.
Watch & Learn : “Scanf Function In C”
Click the following link or else just select the link, copy & paste the link in your browser
https://youtu.be/wedZlcsd8b4

4.2 UN - FORMATTED INPUT/ OUTPUT FUNCTIONS

There are many library functions under this category. We are going to learn few of
them.

Un – Formatted I/O Functions


This function will read a single character, the instant it is typed
getch()
without waiting for the Enter key to be hit.
This function will read a single character and also, it will be
getche() displayed on the screen, without waiting for the Enter key to be
hit
This will read a single character and also, it will be displayed on the
getchar()
screen. But it needs Enter Key to be hit.
This function will read a single character, and also, it will be
displayed on the screen. It also needs Enter Key to be hit. It looks
fgetchar()
similar to getchar(), but getchar() is a macro, whereas fgetchar() is
a function.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 59
`

gets() receives string form the keyboard till enter is pressed


putch()
putchar() These functions will print a character on the screen.
fputchar()
puts() displays string on the output console.
Example 1: (single character - I/O)
void main()
{
char ch;
printf(“enter a character”);
ch=getchar(); // The character read is stored in ch.
putchar(ch);
getchar();
}
Output:

Example 2: (string of characters - I/O) (Note the difference of scanf & gets)
void main()
{
char ch1[20], ch2[20]; //Array / string of 20 characters.
printf(“Enter the second string (through gets)”);
gets(ch2); //reads all characters till enter is pressed.
puts(ch2);
printf(“Enter the first string (through scanf)”);
scanf(“%s”,ch1); // will read all characters till a blank space only
puts(ch1);
getchar();
}
Output:

The moment the blank was typed after “Selva” scanf( ) assumed that the name being
entered has ended. scanf( ) does not take multi word string. The solution to this
problem is to use gets( ) function. The function gets() is terminated when an Enter key
is hit. Thus, spaces and tabs are perfectly acceptable as part of the input string. More
exactly, gets( ) gets a newline (\n) terminated string of characters from the keyboard
and replaces the \n with a \0.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 60
`

Every string is terminated with \0. This is put by the compiler.


Unlike printf( ), puts( ) can output only one string at a time. If we attempt to print two
strings using puts( ), only the first one gets printed. Similarly, unlike scanf( ), gets( ) can
be used to read only one string at a time.

Control Statements:
Now let us move to the topic – Control statements. The statements which we are going
to learn now, have control over the flow of execution of a program, that is why they
are called as “Control Statements”. These are of 4 types:

a. Sequence Control Instruction


b. Selection or Decision Control Instruction
c. Repetition or Loop Control Instruction
d. Case Control Instruction
The Sequence control instruction ensures that the instructions are executed in the
same order in which they appear in the program. Decision and Case control
instructions allow the computer to take a decision as to which instruction is to be
executed next. The Loop control instruction helps computer to execute a group of
statements repeatedly.

4.3 DECISION MAKING STATEMENT – IF …ELSE.

This is the picture of MS Dhoni


tossing a coin, with Virat Kohli.
Before IPL 20-20 match starts, in
order to decide, which team needs
to bat / bowl, the captains will toss a
coin. We’ll interpret this situation as
follows:

Conditional Action: Tossing a coin.


Output of the Action:
a. Head (or) b. Tail
Decided Action to Proceed:
a. if the tossed coin landed with “Head”, Dhoni’s team will proceed to bat
b. else, (otherwise) if the coin landed with “Tail”, Kohli’s team will proceed to bat.

Such decision making conditions exist in C Programs. They control the flow of execution
of the program. There are 2 decision making statements in C. They are:

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 61
`

a. If statements – (bidirectional control statement)


b. Switch Case Statements. – (multi directional control statement)
First we’ll discuss about the “if” statement and its types. “if “statement can be of the
following types:
a. if
b. if…else
c. if…. else if….else
d. nested if
if

Syntax Explanation
if (condition) if the condition returns true, then the
{ statements inside if block will be executed and
_____statements___; then Next statement.
} If false then the block is skipped and the Next
Next statement statement is executed.

Flow Chart
Example:
void main()
{
int a;
printf(“enter a value”)
scanf(“%d”,&a);
if(a<=10)
{
printf(“Less than 11”);
}
getchar();
}

Output:
Enter a value
5
Less than 11
The user has entered the value 5. The value 5 is less than 10. If condition evaluates to
TRUE. The execution therefore enters the if { } block. Hence Less than 11 is printed on
the screen.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 62
`

if… else

Syntax Explanation
if(condition) if the condition returns true, then the
{ statements inside if block will be executed,
_____statements___; otherwise the statements inside else block
} will be executed
else
{
_____statements___;
}

Flow Chart:
Example:
void main()
{
int a;
printf(“enter a value”)
scanf(“%d”,&a);
if(a<=10)
{
printf(“Less than 11”);
}
else
{
printf(“More than 10”);
}
getchar();
}
Output:
Enter a value
15
More than 10

The user has entered the value 15. The value 15 is not less than or equal to 10. If
condition is evaluated to FALSE. Hence the statement inside else block is executed and
the output is More than 10.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 63
`

if… else if …. else

Syntax Explanation
if(condition) The first ‘if’ condition will be checked,
{ if the condition returns true, the
_____statements___; statements inside ‘if’ block will be
} executed and the rest of the ‘else if’
else if (condition) conditions will be skipped from checking.
{
 if false, the control moves to the next
_____statements___;
‘else if’ condition and follows the same
}
else if (condition) rule.
{ if all the if and else if conditions return
_____statements___; false, then else block statement will be
} executed.
….
…..(any number of else if conditional
statements are allowed)
…..
else
{
_____statements___;
}

Flow Chart:
Example:
void main()
{
int a;
printf(“enter a value”)
scanf(“%d”,&a);
if(a<=5)
{
printf(“Less than 6”);
}
else if (a>5 && a<=10)
{
printf(“In 6 to 10”);
}
else
{
printf(“more than 10”);
}
getchar();
}

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 64
`

Output:
Enter a value
7
In 6 to 10
The user has entered the value 7. The value 7 is not less than or equal to 5. So, the first
‘if’ condition fails. Then it checks the ‘else if’ condition, in which the value 7 lies between
6 and 10, hence the output “In 6 to 10”.
Nested if
If we write an entire if-else construct within either the body of the if statement or the
body of an else statement. This is called ‘nesting’of ifs.
Example:
void main()
{
int a;
printf(“enter either 1 or 2”);
scanf(“%d”,&a);
if(a==1)
{
printf(“Good Morning”);
}
else
{
if(a==2)
{
printf(“Good Afternoon”);
}
else
{
printf(“Good Night”);
}
}
getchar();
}
Output:
Enter either 1 or 2
5
In 6 to 10

The user has neither entered 1 nor 2. So, the innermost else statement, inside the else
statement is executed and hence the output “Good Night”.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 65
`

Watch & Learn : “if Statements in C ”


Click the following links or else just select the links, copy & paste the links in your browser
https://youtu.be/4R_CE2zbHNk
https://youtu.be/zf4HKkixouU
https://youtu.be/yXGhtygJ6c8

4.4 DECISION MAKING STATEMENT – SWITCH


Have you ever called to a customer Service? Once you get connected, they will give you
options for choosing the language. It goes like this…Press 1 for Tamil, 2 for English, 3
for Hindi etc. Next action will be based on the option chosen.

This is the same case with switch case. We have multiple choices, we would choose
one that suites us. Based on the choice the program execution continues. For this
reason why, switch is called as Multi-directional Control Statement.

Syntax Explanation

switch (expression) a. switch statement is multi- directional control


{ statement, mainly used for making a particular
case 1: choice from the many choices.
statements; b. Based on the expression’s output, case will be
break; chosen and the statement inside the
corresponding case will be executed.
case 2:
c. Switch block has three main elements. They
statements;
are:
break;
a. Expression

b. Case
…..(any number of cases
c. Break
can be included)
d. The output of an expression can be integer or
….
char data type, or even Character constants or
case n:
Integer constants.
statements;
break;

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 66
`

e. The case values can be either integer or char


default: constants. This depends on the expression we
statements; are going to use.
break; f. break statement is necessary at the end of each
} case, in order to move out of the switch block,
as soon as the case is executed.

Flow Chart:

Example:
#include<stdio.h>
void main()
{
int choice;
printf("Welcome to NTTF customer support");
printf("\n Our Customer Care Person will contact you soon");
printf("\n Please choose your choice of language 1- English, 2- Tamil, 3- Kannada, 4-
Hindi");
scanf("%d",&choice);
switch(choice)
{
case 1:

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 67
`

printf("Good Day Sir!");


break;
case 2:
printf("Vanakkam Sir!");
break;
case 3:
printf("Namaskara Sir!");
break;
case 4:
printf("Namaste Sir!");
break;
default:
printf("How can we help you Sir!, please make a correct choice!");
break;
}
printf("\nNTTF is Nettur Technical Training Foundation. Visit our website
www.nttftrg.com for more details\n");
getchar();
getchar();
}
Output:
Welcome to NTTF customer support
Our Customer Care Person will contact you soon
Please choose your choice of language 1- English, 2- Tamil, 3- Kannada, 4- Hindi
2
Vanakkam Sir!
NTTF is Nettur Technical Training Foundation. Visit our website www.nttftrg.com for
more details

Watch & Learn : “Switch Statement in C ”


Click the following link or else just select the link, copy & paste the link in your browser
https://youtu.be/S7-8Auntzlk

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 68
`

Some Tips & Traps in switch statement:


a. Case values need not be in ascending order
b. If the value (or) the character (or) the output of the expression inside switch is not
matching with the case values, then default case will be executed. But default case
is optional. If no default case is written, especially for wrong choices, No case will
be executed and the control comes out of the switch statement.
c. We are allowed to use int and char values in case.
d. If we want to use same set of statements for 2 different cases, it can be managed
as follows:
case ‘a’:
case ‘A’:
printf(“A for Android”);
break;
e. Even if there are multiple statements to be executed in each case there is no need
to enclose them within a pair of braces
f. All that we can have after the case is an int constant or a char constant or an
expression that evaluates to one of these constants. Even a float is not allowed.
g. We can check the value of any expression in a switch. Thus the following switch
statements are legal.
switch ( i + j * k )
switch ( 23 + 45 % 4 * k )
switch ( a < 4 && b > 7 )
h. Expressions can also be used in cases provided they are constant expressions. Thus
case 3 + 7 is correct, however, case a + b is incorrect.
i. The break statement when used in a switch takes the control outside the switch.
However, use of continue will not take the control to the beginning of switch as
one is likely to believe.
j. In principle, a switch may occur within another, but in practice it is rarely done.
Such statements would be called nested switch statements.
k. The switch statement is very useful while writing menu driven programs.

Watch & Learn : “Need for Decision Making statements”


Click the following link or else just select the link, copy & paste the link in your browser
https://youtu.be/G_zb__cV9Xk

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 69
`

4.5 LOOPING STATEMENTS - FOR, WHILE, DO-WHILE

Looping control enables a set of statements to execute repeatedly till till the condition
evaluates to TRUE.
Looping control statements in C include:
a. for statement
b. while statement
c. do-while statement

All the looping controls will have these steps:


a. Initialisation
b. Condition for execution of the loop
c. Repeated statements for execution.
Consider the following scenario to understand looping control:
A father is having 100 rupees in his wallet. He promised to give Rs 10 to his son daily,
by taking the money from his wallet, provided with a condition, that the father will stop
giving Rs 10 to his son, once the wallet becomes empty.

Initialised Activity: Father’s Wallet with Rs 100


Repeated or Looping Activity: Rs 10 will be given to the son
Condition : Provision of Rs 10(repeated activity) to the son, will not be stopped until
the wallet is not empty.

Another real time example could be, the reactors located in big plants must run under
certain pressure and temperature. The reactions inside the reactor will be continuously
occurring 24*7, until the pressure and temperature are maintained correctly. If any
deviations occur in temperature and pressure, the plant would have setups to stop the
reactor immediately.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 70
`

Watch & Learn : “Need for Loops”


Click the following link or else just select the link, copy & paste the link in your browser
https://youtu.be/FFiDX6akfKE

For Loop
for loop has these three elements stated in a single line.
for loop is an entry controlled loop, since the flow of control of looping is allowed, only
if the condition is checked and satisfied, at the entry of the loop.
Syntax:
for(initialisation of counter variable; condition check; Increase or decrease the loop
counter)
{
statements;
}
We’ll learn the control flow of ‘for’ loop with the help of an example
//Print the values from 0 to 5

void main()
{
int i;
for(i=0; i<=5; i++)
{
printf(“\t%d”,i);
}
getchar();
}

Output
0 1 2 3 4 5

Flow chart: (for the above program as follows)

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 71
`

a. Initialisation in ‘for’ loop will be done only once.


b. For the above program for printing the values 0 to 5, the value of i is initialised to 0.
This is the first step in for loop, and is done only once.
c. The next step will be, the value of i, will be checked against the condition, i<=5. ie)
now the value of i is 0 and it will be checked as 0<=5.This condition is true.
d. Since the condition is true, the control will move inside the for loop to print the value
of i, which is now 0.
e. Then to proceed with the loop, the value of i is incremented by 1. the current value
of i is now 0+1 = 1. This i is again checked with the condition i<=5,ie) 1<=5, which is
also true. So, again the control enters the loop and prints the value of i as 1.
f. These steps will be repeatedly done, until the condition become false. ie) when the
value of i incremented to value 6, the condition fails, and the loop ends.
Nested for loop
If a for loop is present within another for loop, then it is called as nested for loop.
Example:
void main()
{
int i, j;
for (i=1; i<=2; i++)
{
for(j=11; j<=12; j++) // inner loop or Nested for loop
{
printf(“%d\t”, j);
}

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 72
`

printf(“\n”);
}
getchar();
}
Output:
11 12
11 12

Lets see the above example’s flow chart, which would explain clearly the flow of
control. (You can easily interpret the following flow chart, with the explanation you
learnt from the previous flow chart of ordinary ‘for’ loop)

Watch & Learn : “For Loop ”


Click the following link or else just select the link, copy & paste the link in your browser
https://youtu.be/l6HzdW65c4I

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 73
`

While Loop

while loop is also an entry controlled loop, since the flow of control of looping is
allowed, only if the condition is checked and satisfied, at the entry of the loop
Syntax:
while(condition)
{
statements;
}

The condition in while will be checked, if the condition is true, the statements inside
the while block will be executed repeatedly, until the condition becomes false. In the
beginning itself, if the condition in while is not true, the control will skip the while block
and move to the next line of while loop.

The while loop also has 3 elements, wherein, initialisation is done outside the while
loop, condition checking along with the while statement and the increment or
decrement of counter variable to do the repeated flow of execution of statements, will
be present inside the while loop.
Flow Chart:

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 74
`

Example:
// Printing values 1 to 10 in reverse order
void main()
{
int i=10 //initialisation
while(i>=1)
{
printf(“%d \t”, i);
i--;
}
getchar();
}
Output:
10 9 8 7 6 5 4 3 2 1

In the above example, the value of i is initialised to 10. In while loop, the condition
whether the value of i is greater than or equal to 1is checked. Ie. 10>=1. This is true and
so, the value of i  10 is printed on the screen with a tab space. The value of i is
decremented by 1 ie. 10-1 =9 and then i=9, is checked again for the condition in while,
9>=1. This is also true and so, 9 is printed on the output screen with a tab space. These
actions will be done again and again until the condition becomes false, ie. when the
value of i becomes 0, 0>=10, will not be satisfied. So, the while loop stops execution
and the control comes out of the while loop.
Watch & Learn : “While Loop ”
Click the following link or else just select the link, copy & paste the link in your browser
https://youtu.be/A0ZzFqbJ9sM

do - while Loop

do – while loop is an exit controlled loop, since the condition for executing the control
of flow of loop, is checked only at the exit of the loop.
Syntax:
do
{
statements;
} while(condition);

In do-while loop, since the condition is checked at the end of the loop, loop is executed
atleast once for false condition.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 75
`

Flow Chart:

Program:// Printing values 1 to 10 in reverse order


void main()
{
int i=10
do
{
printf(“%d \t”,i);
i--;
} while(i>=1);
getchar();
}
Output:
10 9 8 7 6 5 4 3 2 1
In the above example, the value of i is initialised to 10. The control now enters the do
– while loop. The value of i  10 is printed on the output console with a tab space.
Here for entering the do-while loop, no condition is checked. Now, the value is
decremented by 1. ie) 10-1 =9. At this point the control will try to exit the loop, but
there is a while condition, which checks 9>=1. Thereafter, this will behave like an
ordinary while loop. Since, this condition is true, the body of the loop will be executed,
by printing 9 on the output screen and the flow continues, until the condition becomes
false.
Watch & Learn : “Do-while loop, how it is different from while loop ”
Click the following link or else just select the link, copy & paste the link in your browser
https://youtu.be/O3ZLlRz4M-s

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 76
`

Difference between while and do-while loop


while loop do – while loop
while loop is an entry controlled loop do-while loop is an exit controlled loop
while loop checks the condition at the do-while loop checks the condition at the
beginning of the loop itself exit of the loop

do – while loop, enters the loop and


while loop checks the condition first,
executes the statements, atleast once,
only if the condition is true, the control
even the condition is false. After
flows inside the loop and the statements
executing once, the while condition will
inside the loop will execute repeatedly,
be checked and thereafter the loop
until the condition becomes false.
behaves like an ordinary while loop.

In the syntax of while loop, the while In the syntax of do - while loop, the while
condition statement does not end with a condition statement ends with a
semicolon. semicolon.
Syntax: Syntax:
while(condition) do
{ {
----------- -----------
statements; statements;
----------- -----------
} } while(condition);

4.6 BREAK, CONTINUE, GOTO STATEMENTS


Break Statement
We often come across situations where we want to jump out of a loop instantly,
without waiting to get back to the conditional test. The keyword break allows us to do
this. When break is encountered inside any loop, control automatically passes to the
first statement after the loop. Break is usually associated with an ‘if’.
Syntax:
break;
Program:
void main()
{
int i;
for(i=1; i<=5; i++)
{
if(i==3)

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 77
`

{
printf(“exiting the loop\t”);
break;
}
printf(“%d\t”,i);
}
printf(“\nThank you”);
getchar();
}
Output:
1 2 exiting the loop
Thank you
In this program, the ‘for’ loop actually runs for i values, varying from 1 to 5. But
inside the for loop, we have written an ‘if’ statement, that if the value of i is 3, ‘break’.
That is why, when i value is turned to 3, break statement exits from the current ‘for’
loop and moves to the next line of the loop, printing ‘Thank You’.

Watch & Learn : “Need of Break statement ”


Click the following link or else just select the link, copy & paste the link in your browser
https://youtu.be/nRddDZWIcak

Continue Statement
In some programming situations we want to take the control to the beginning of the
loop, bypassing the statements inside the loop, which have not yet been executed. The
keyword continue allows us to do this. When continue is encountered inside any loop,
control automatically passes to the beginning of the loop. A continue is usually
associated with an if.
Syntax:
continue;
Program:
void main()
{
int i;
for(i=1; i<=5; i++)
{
if(i==3)
{
printf(“skipping this part of the loop\t”);

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 78
`

continue;
}
printf(“%d\t”,i);
}
getchar();
}
Output:
1 2 skipping this part of the loop 4 5

In this program, the ‘for’ loop actually runs for i values, varying from 1 to 5. But inside
the for loop, we have written an ‘if’ statement, that if the value of i is 3, ‘continue’. That
is why, it has skipped the part of the loop and moved to the first line of the loop. So, in
the output printed, we have not seen 3 printed.

Difference between break and continue


Break Continue
break statement will exit from the continue statement will skip a part of the
current loop and move to the next line of loop and move to the first line of the
the loop current loop
Syntax: break; Syntax: continue;

Goto Statement:
Goto is an unconditional control statement. It takes the control from one part of the
program to another part of the program, without any condition.
The syntax of goto statement is
goto label;
---------
---------
-------
label:
____

Label can be placed anywhere in a program, either before goto or after goto statement.
If the label is present before the goto statement, the control makes a backward jump.
if the label is present after the goto statement, the control makes a forward jump.

goto statement disturbs the flow of execution of a program. So, a good programmer
must avoid using goto statement, unless it is unavoidable.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 79
`

Program:
void main()
{
int i;
for(i=1;i<=5;i++)
{
if(i==3)
{
goto a;
}
printf(“%d\t”,i);
}
a:
printf(“Thank you!”);
getchar();
}
Output:
1 2 Thank you!

4.7 INFINITE LOOP

A loop that repeats indefinitely and never terminates is called an Infinite loop.
Most of the time we create infinite loops by mistake. However, this doesn’t mean that
the infinite loops are not useful. Infinite loops are commonly used in programs that
keep running for long periods of time until they are stopped like the web server.

Infinite loop by mistake


Example:
void main()
{
int i=10;
while(i>=10)
{
printf(“%d\n”,i)
i++;
}
getchar();
}

If you see the above program, the value of i is initialised to 10. The condition to enter

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 80
`

while loop is given as i>=10. Since i value is 10 now, the condition is true and it enters
while loop, printing 10 on the output screen. The loop continues by incrementing the
value of i.ie) i value will be varying as 11, 12, 13, 14…. and all these values will be
satisfying the while loop condition. This may lead to infinite looping. This infinite
looping had occurred due to human error/mistake in typing / carelessness.

Infinite loop for a purpose

Sometimes, we need this infinite looping, in our program which need to run for long
time, repeatedly doing the same action all the time, until the programmer/user stops
it.

This can be done with the help of introducing while(1) statement in our program. The
following program will display the menu of different arithmetic operations, until the
user chooses his choice for exit. (Try this in your laptop….you will understand better)

Program:

#include<stdio.h>
void main()
{
int a, b, c, n;
char ch;
while(1)
{
printf("\n\nenter your choice of operation: \n1=addition, \n2=subraction,
\n3=multiplication, \n4=division, \n5=modular division \n6=Exit \n");
scanf("%d",&n);
switch(n)
{
case 1:
printf("\nenter the two values");
scanf("%d%d",&a,&b);
c=a+b;
printf("the sum is %d",c);
break;
case 2:
printf("\nenter the two values");
scanf("%d%d",&a,&b);

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 81
`

c=a-b;
printf("the difference is %d",c);
break;
case 3:
printf("\nenter the two values");
scanf("%d%d",&a,&b);
c=a*b;
printf("the product is %d",c);
break;
case 4:
printf("\nenter the two values");
scanf("%d%d",&a,&b);
c=a/b;
printf("the quotient is %d",c);
break;
case 5:
printf("\nenter the two values");
scanf("%d%d",&a,&b);
c=a%b;
printf("the reminder is %d",c);
break;
case 6:
goto a; //break;
default:
printf("enter the choice is wrong");
break;
}
getchar();
}
a:
}

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 82
`

Output:

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 83
`

Time to recall & Test yourself!

1. Why do we call scanf() & printf() as ‘formatted’ input and output functions?
2. What are the control statements, we can use to repeat a certain set of code in a
program?
3. Can the programs written through ‘while’ loops, be re-written through ‘for’ loops?
Justify your answer with the help an example.
4. do-while loop is useful when we want that the statements within the loop must be
executed:
a. Only once b. At least once
c. More than once d. Atmost once
Extra Note: The initialisation expression of the for loop can contain more than one
statement separated by a comma. For example,
for ( i = 1, j = 2 ; j <= 10 ; j++ )
Multiple statements can also be used in the incrementation expression of for loop;
i.e., you can increment (or decrement) two or more variables at the same time.
However, only one expression is allowed in the test expression. This expression may
contain several conditions linked together using logical operators.
5. Is there any error spotted in the following program? (Execute in your laptop and find
it)
void main()
{
char another = 'y' ;
int num ;
for ( ; another == 'y' ; )
{
printf ( "Enter a number " ) ;
scanf ( "%d", &num ) ;
printf ( "square of %d is %d", num, num * num ) ;
printf ( "\nWant to enter another number y/n " ) ;
scanf ( " %c", &another ) ;
}
getchar();
}
6. The break statement is used to exit from:
a. an if statement
b. a for loop
c. a program
d. the main( ) function

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 84
`

7. Which of the following is not an infinite loop. (Run the programs and find out)
a) b)
int i = 1 ; for ( ; ; ) ;
while ( 1 )
{
i++ ;
}
c) d)
int True = 0, false ; int y, x = 0 ;
while ( True ) do
{ {
False = 1 ; y=x;
} } while ( x == 0 ) ;

8. Which of the following statement is used to take the control to the beginning of
the loop?
a. exit
b. break
c. continue
d. None of the above
9. Variable x = 23.463. Write the printf statement to print as “x = 23.5”.
10. name[ ]=”NTTF”. What is the expected output of the statement : printf(“ I \t am
\n in %.3s”, name);
11. What is the difference between scanf(“%s”, str ); and gets(str);
12. Differentiate break and continue statement with an example.
13. Explain ‘switch case’ with example.
14. Which statement is used to come out from the switch case statement?
a. exit b. break c. goto d. stop
15. Which of the following cannot be checked in a switch-case statement?
a. integer b. float c. character d. enum
16. When a break statement is encountered inside a loop, which of the following
occur ( )
a. Control goes to the end of the program. b. Control exit the full
program
c. Causes an exit from the innermost loop containing it d. None of the
above
17. Write code to print multiplication table of 6.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 85
`

UNIT - 5
ARRAYS

To understand the concept of array, let us first recall the ordinary variable declaration
and the way in which it is occupied in the memory.

Declaration of an ordinary variable


int a;
char ch;
A 2 bytes memory with the name ‘a’ is allotted for storing an integer element and one
byte for storing a character variable with ch as its name.

The memory space ‘a’ is capable of storing only one integer value. Similarly ch can store
only one byte of character type data.

Suppose we want to store marks of 50 students, then we will have to create 50 variables
with 50 different names. C program makes this task easier by giving us a facility to store
all 50 marks in contiguous memory locations with only one name. Some thing like a list.
This concept of allotting contiguous memory location for same type data is called
“Array”.

Definition of Array:
Array is a group of same data type elements, which are stored under a single
name, in contiguous memory locations.

The above words which are in bold & underlined are self-explanatory, except
contiguous memory locations.

There is a major difference between


continuous and contiguous memory
locations.

Array means “Arrangement”. Continuous


and Contiguous can be differentiated and
explained clearly by the way the elements
are arranged.

Continuous Arrangement

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 86
`

Consider the seating arrangement in a theatre.


a. Group of people assemble in the theatre
b. The theatre seats are numbered from 1 to 200 according to the capacity of the
theatre.
c. The individual members are seated starting from the seat number 1 to 200.
This is called as continuous arrangement.

Now we’ll co-relate this scenario with continuous memory locations.


Group of elements when they are arranged in the memory locations starting from 1001
to 1005, then it is called as “Continuous” arrangement of elements in the memory.

Contiguous Arrangement
Now we’ll have a look on contiguous arrangement.

a. Consider a bench in a classroom

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 87
`

b. For this example, let us imagine, Group of kids of same age & equal size try to sit
on the bench.
c. Here, there is no numbering done on the bench. But the kids occupy the space
based upon their size.
d. The kids are equally seated / arranged one after the other based upon their size.
(Here assume all kids are of equal size)
e. Now, assume that the kids have gone and on the same bench teenagers of same
age and equal size sit. Each teenager requires more space than the kids.
f. These teenagers also occupy the space equally and are seated one after the other.

Let us now correlate this with contiguous arrangement.

Group of same data type elements are arranged in the memory one after the other,
based upon their data size. This is contiguous arrangement of elements in the memory.
Example 1: If there are 5 integer elements, they would occupy 2 bytes each, in
contiguous memory locations say 1001, 1003, 1005, 1007, 1009 etc, when they are
stored as array.

Example 2: In the same manner, If there are 5 floating point data elements, they would
occupy 4 bytes each, in contiguous memory locations of addresses say 1001, 1005,
1009, 1013, 1017, etc when they are stored as array.

So, whenever you write the definition for Array, never write continuous memory
locations, because array elements are stored in contiguous memory locations and not
in continuous memory locations.

Types of Array
a. Single Dimensional Array
b. Multi-Dimensional Array

5.1 Single Dimensional Array

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 88
`

Array holds the same definition as we saw few lines before. But the types are defined
and differentiated by the way they are declared.

Declaration of Single Dimensional Array


Syntax:
datatype arrayname[size of the array];
Examples: int a[5], x[15]; float mark[25];

The word dimension is based on the number of subscripts we use. Subscript is the
square bracket [ ]we have used here.

In the above declaration, we have used only one subscript, so is the name Single
dimensional array. Also, the nature of its storage also specifies its type.
Let us see now, how the above declaration is depicted.
Consider int a[5]. It is an array of name ‘a’, capable of storing 5 integer elements.
(Remember array cannot store different data type elements).

Since the array has a single name ‘a’, the


elements in an array can be identified by
having an index number, starting from 0 to n
- 1, where ‘n’ is the size of the array. The first
element is identified by the name a[0], the
second element by a[1] and so on. So, Single
dimensional array is a homogenous (same data type) group of elements stored in a
linear form.

Initialisation of Single Dimensional Array


Initialisation of an array, is assigning values to the array indices.
This can be done in the following ways:

a. Declaration and then initialization.


int a[5];
a[0]=2;
a[1]=10;
a[2]=5;
a[3]=7;
a[4]=9;
b. Initialisation along with declaration
int a[5]={2, 10, 5, 7, 9};

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 89
`

c. Initialisation along with declaration, but without specifying the array size
int a[]={2,10,5,7,9};

If the array is initialized during declaration then mentioning the dimension of the array
is optional. But there is a difference.
int a[10]={2, 10, 5, 7, 9};
10 location declared but only first 5 are initialized. If an array is partially initiated at the
time of declaration then the remaining elements of the array will be initialized to 0 by
default.
int a[]={2,10,5,7,9}; // only 5 locations declared and initialized.

Also, to note that, if we fail to initialise the value for an array element, the compiler
would assign a garbage value to it.

Getting the values for a single dimensional array from the user and printing it:
void main()
{
int a[10], n, i;
printf(“enter the number of elements”);
scanf(“%d”,&n);
printf(“enter the elements”);
for(i=0; i<n; i++) // this for loop runs for the index 0 to n-1
{
scanf(“%d”,&a[i]);
} //end of for loop
printf(“The elements are:”);
for(i=0; i<n; i++)
{
printf(“%d\t”,a[i]);
} // end of for loop
getchar();
}
Output:
enter the number of elements
5
enter the elements
2
4
8
9
100
The elements are:2 4 8 9 10

Some more points to understand:


 Name of array = address of array = address of array[0].

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 90
`

 if int a [10]; is declared as an array,


then a+1 = address of 2nd element
a + 2 = address of 3rd element

Let us see a simple example to understand it.

#include<stdio.h>
void main()
{
int a[3];
printf("enter the first element");
scanf("%d",a); //we have used a instead of &a[0] since a = address of a = address of a[0](first element)
printf("\nThe first element is %d",a[0]); // a[0] can also be replaced by *a
printf("\n\nenter the second element");
scanf("%d",a+1); //&a[1] can be written as a+1
printf("\nThe second element is %d",a[1]); // a[1] can also be replaced by *a+1
printf("\n\nenter the third element");
scanf("%d",a+2); //&a[2] can be written as a+2
printf("\nThe third element is %d",a[2]); // a[2] can also be replaced by *a+2
getchar();
}

Output:

5.2 Multi Dimensional Array


We can declare multiple dimensional array. We will limit ourselves to 2 and 3

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 91
`

dimensional arrays.

Two Dimensional Array

Two dimensional arrays are arrays declared with 2 subscripts.


Two-dimensional arrays are understood as rows and columns with applications
including two-dimensional table and two-dimensional matrices. We can consider two-
dimensional array as ‘array of array’.

Declaration of Two dimensional Array


datatype arrayname[rowsize][column size];
int a[2][3]; float mark[3][10];
The first subscript specifies the row size and the second subscript specifies the column
size.
Two dimensional array is a homogenous group of elements stored in a tabular form.
Total number of elements that can be stored in a two dimensional array = row
size*column size
Total number of elements in int a[2][3] are 2*3 = 6 elements
The declaration of two dimensional array can be depicted as
given in the picture.

Initialisation of Two dimensional Array


Initialisation can be done in the following ways:
a. Initialisation after declaration.
int a[2][3];
a[0][0]=2;
a[0][1]=3;
a[1][2]=5;
b. Initialisation along with declaration.
int a[2][3]={
{10, 2, 7},
{5, 3, 9}
};
c. (or)
int a[2][3]={10,2,7,5,3,9};
d. Initialisation without specifying the row size
int [][3]={10,2,7,5,3,9};

whereas, int[][]={10,2,7,5,3,9}; & int [3][] ={10,2,7,5,3,9}; will not work.


Getting the values for a single dimensional array from the user and printing it: (Matrix
printing)

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 92
`

void main()
{
int a[10][10], i, j, n, r, c;
printf(“enter the size of row & column”);
scanf(“%d%d”,&r,&c);
printf(“enter the elements of array”);
for(i=0; i<r; i++)
{
for(j=0; j<c; j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“the two dimensional array is:\n”);
for(i=0; i<r; i++)
{
for(j=0; j<c; j++)
{
printf(“%d\t”,a[i][j]);
}
printf(“\n”);
}
getchar();
}
Output:
enter the size of row & column2 2
enter the elements of array3 7 9 2
the two dimensional array is:
3 7
9 2

Three Dimensional Array:


Three dimensional arrays are arrays declared with 3 subscripts.
We can consider two-dimensional array as ‘array of arrays’.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 93
`

Declaration & initialisation of three dimensional array


int a[2][3][2]; // 2 rows and 3 columns of array of 2 elements each
int arr[2][3][2]={
{2, 4}, {7, 8}, {3, 4},
{7, 6}, {3, 4}, {5, 3},
};

5.3 Strings in C
Group of characters that are stored in a character array is called as string.
A string constant is a one dimensional array of characters terminated by a null
character (‘\0’). For example, char name[]={‘N’,’T’,’T’,’F’,’\0’};

character occupies one byte in the memory and the last character is always ‘\0’.
The initialisation is also possible as, char name[]=”NTTF”;
Here, ‘\0’ is not necessary. It is added by the compiler when we compile the program.

Program to print “NTTF” using while loop.


#include<stdio.h>
void main()
{
char name[]="NTTF";
int i=0;
while(name[i]!='\0')
{
printf("%c ",name[i]);
i++;
}
getchar();
}
Output:
N T T F

Getting the string using scanf() and displaying the string using printf()
#include<stdio.h>
void main()
{

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 94
`

char name[20];
printf("enter your college name");
scanf("%s",name); // string variables do not need & symbol in scanf().
printf("the name of my college is:%s",name);
getchar();
}
Output:

While entering the string using scanf(), we must be cautious about the following:
a. The length of the string should not exceed the dimension of the character array.
b. scanf() is not capable of receiving multi word strings. For example “NTTF is my
college”. This limitation can be overcome, by using gets() function.
Example:
void main()
{
char name[30];
printf(“Enter a string: ”);
gets(name);
puts(name);
getchar();
}
Output:
Enter a string: NTTF is my college
NTTF is my college

Making scanf() to accept multi word string:


void main()
{
char name[20];
printf("enter your college name");
scanf("%[^\n]s",name);
printf("the name of my college is:%s",name);
getchar();
}
Output:

Here, [^\n] indicates that scanf() will keep receiving the characters into name until \n
is encountered.

Time to recall & Test yourself!

1. If a static array is not initialized, the elements in an array will be set to

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 95
`

a. 0 b. undetermined value c. floating point value d. ’\0’

2. String to be entered is “My name is Rohit”. Which of the following will read the string
correctly:
scanf(“%s”, name);
gets(name);

3. We have to read two datas i) “A” and ii) ‘a’. Declare appropriate variables and write
suitable scanf function for both.

4. Which character is used to terminate a string?

5. You have written


int i, x[10];
for (i=0; i<20; i++)
x[i]=i;
What will happen?
a. system malfunction b. nothing
c. other data may be overwritten d. error message from the compiler

6. You have written


int i, x[10];
for (i=0; i<5; i++)
x[i]=i;
What will happen?
a. system malfunction b. nothing
c. unused elements will be filled with 0’s or garbage values
d. error message from the compiler

7. int i, j, m, a[5] = {5, 1, 15, 20, 25};


i = ++a[1];
j = a[1]++;
m = a[i++];
printf(“ %d %d %d”,i, j, m);
which of the following will be the output?
a. 3, 2, 15 b. 2, 3, 20 c. 2, 1, 15 d. 1, 2, 5

8. char p, buf[10] = {1, 2, 3, 4, 5, 6, 9, 8};


p = (buf+1)[5];
printf(“ %d ”,p);
which of the following will be the output?

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 96
`

a. 5 b. 6 c. 9 d. error
9. Let be an array. Which of the following operations are illegal?
a. ++x b. x+1 c. x++ d. x*2

10. int arr[10] = {1, 2, 3, 4, 5};


Printf(“%d”, arr[5]);
which of the following will be the output?
a. Garbage value b. 5 c. 6 d. 0

11. char str1[] = “abcd”;


char str2[]= “abcd”;
if (str1 ==str2)
printf(“Equal”);
else
printf(“Unequal”);
which of the following will be the output?
a. Equal b. Unequal c. error d. abcd

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 97
`

UNIT - 6
FUNCTIONS
6.1 FUNCTION - LIBRARY AND USER DEFINED FUNCTIONS, ELEMENTS OF
FUNCTION

A Grand Mother gives instructions to her Grand Daughter, to prepare tea.

Let us interpret this scenario with our function concept.


“Grand Mother” can be related to “Programmer”.
“Grand Daughter” can be related to “Computer / C Compiler” (which runs C
programs).
“Instructions to prepare Tea” can be related to “The set of code”.
“Instructions to prepare tea, noted on a paper” can be related to “The set of code
within a block”.
“Tea” can be related to “The desired task / output”.
The programmer writes set of instructions as programs and feeds into the computer
to get the desired output.
In C Programming, the set of instructions are written within a block and we call it as
function.

What is function?
Function is a self-contained block of statements, which is used to define a particular
task.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 98
`

Types of Function:

User Defined Functions


We’ll go back to the same example which is stated above.

Scenario 1
The Grandmother gives instructions on a paper, about the process of preparing tea. In
the same manner, the programmer writes a set of instructions within a block, to
perform a desired task.

If the block of instructions are written, by the programmer, in order to do a particular


task, then it is called as “User Defined function”

Example:
void main() is a user defined function, since the code is written by the programmer
according to his/her desire of output.

Users / the programmers can create their own functions and add them to the main
program as functions. These functions can be given any name, but follow the naming
rules of an identifier. factorial(), getdetails(), sum(), analyse(), etc.,

Pre Defined Functions / Library Functions:


Scenario 2

In the above example about process of preparing Tea, the instructions are given on the
paper. It tells the Grand daughter to “Add Tea powder”, “Add Sugar” etc.

The granddaughter will now move to the shelf and take the tea powder & sugar, and
add to the milk. In the same manner, there are certain set of codes which are already
defined / written and kept in header files.

Those block of code, which are already written and defined inside the header files,
we call them as “Library functions” or “Pre-defined functions”

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 99
`

When we need it in our program, we call it to execute it.


Examples:
a. The definitions of the standard input/ output functions such as scanf() & printf() are
defined in the header file stdio.h
b. The definitions of console input output functions such as, getch() & clrscr() are
defined in the header file conio.h
c. The definitions of mathematical functions such as pow(), sqrt() are defined in the
header file math.h
d. The definitions of string functions such as strlen(), strcpy(), strcat() are defined in
the header file string.h

Elements of Function
a. 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 and
may not return value. In this case, the return_type is the keyword void.
b. Function Name − This is the actual name of the function. The function name and
the parameter list together constitute the function declaration.
c. 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; ie. a function may not contain
any parameters.
d. Function Body − The function body contains a collection of statements that define
what the function does.

Function Declaration (name) and function return type

Function declaration is about telling the compiler,


a. The name of the function.
b. The types of parameters, it accepts from the calling function.
c. Type of the return value
(The words in bold will be explained under “6.2 – Four categories of functions”)

Syntax for Function Declaration:


return-type function_name(list of types of parameters);

Example : int analyse(int, float);

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 100
`

Function Call:
When a particular block of code written as a function need to be executed, it will be
called using its name. A function can be called any number of times. This concept
enhances the re-usability of code.

Syntax for Function Call:


return value = function_name(list of arguments without specifying the data type);
Return value is optional and will be used if the function is returning a value.
Example: x = analyse(a, b);

Function Definition:
The piece of code within a block, which defines a specific task is called as the definition
of the function.

Syntax for Function Definition:


return-type function_name(list of parameter along with their data types)
{
_____
___
}

Example: int analyse(int c, float d)


{
set of instructions;
return y;
}
Recall the structure of C –Program, we have learnt in Unit2. Follow how the elements
of a function are implemented in a program, with the help of diagram given below:

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 101
`

6.2 FOUR CATEGORIES OF FUNCTIONS


a. Function without arguments and no return value
b. Function with arguments but no return value
c. Function without arguments but with return value
d. Function with arguments and with return value
Before learning the various categories of function, we must understand the definition
of 2 things.
a. Argument – It is a value that is passed to a function when it is invoked.
b. Parameter – It is a variable defined in the function definition that receives a value
when the function is called.

Category 1: Function without arguments and no return value


Consider a class room, in which a teacher calls a student “Rita” and asks her to go to
the staffroom and check whether the clock shows 10:10 am and come back.

Here,
 The main function is the Teacher
 The called function is Rita
 The function defined for Rita is to go to the staffroom, check whether the time is
10.10 am or not.
Things to Note: Rita didn’t take any object from the teacher. Also, after checking the
time, she didn’t bring any object from the staffroom.
In the same way, if the called function didn’t take any value (argument) from the main
function and didn’t return any value to the main function, after performing its task,
then the function falls under the category “Function without argument and no return
value”.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 102
`

Syntax for Function Declaration:


return-type function_name(list of types of parameters);

The function declaration statement used in the above example:


void function1();
a. The return type is void, since no value is returned back from sub function –
function1, to the main function.
b. Also the list of type of arguments are left blank, since no value is taken from the
main function to the called function.

Function Call
Syntax for Function Call:
function_name(list of arguments without specifying the data type);
The function call statement used in the above example:

function1();
The list of arguments without specifying the data type - are left blank, since no value is
passed to the sub function – function1().

Function Definition
Syntax for Function Definition:
return-type function_name(list of parameter along with their data types)
{
_____
}

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 103
`

The function definition statement used in the above example:


void function1()
{
___
}
a. The return type is void, since no value is returned back from sub function –
function1, to the main function.
b. List of parameters along with their data types are left blank, since no value is
taken from the main function to the called function.

Category 2: Function with arguments and no return value


Consider the same classroom, in which the teacher calls Rita and gives Rita, her bag.
The teacher asks Rita to keep the bag in the staff room and come back.
In this scenario,
a. Rita takes the bag from the teacher.
b. Keeps it in the staff room and returns back to the teacher without any object in her
hand.
In the same way, if the function called takes a value from the main function but it does
not return any value to the main function, after performing its task, it falls under the
category, “Function with argument but no return value”.

Compare the changes in the elements of function as we did for the first category.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 104
`

Category 3: Function without arguments but with return value

Now, the teacher asks Rita to go the staff room and arrange the apples in the basket
and bring the basket of apples to the class room.
In this scenario,
a. Rita takes nothing from the teacher.
b. She goes to the staffroom arrange the apples in the basket and brings back to the
teacher the basket full of apples.
In the same way, if the ‘called function’ didn’t take any value from the main function,
but it returns a value back to the main function after performing its task, then it falls
under the category “Function without arguments but with return value”.

Category 4: Function with arguments and with return value


The teacher gives Rita a set of books and asks her to keep it on her table. Also while
returning from the staffroom, the teacher has asked Rita to bring her handbag to the
class room.

In this scenario,
a. Rita takes set of books from the teacher
b. She goes to the staffroom keeps the books on the table and while returning back,
she is bringing an object -handbag, in her hand.
In the same way, if the ‘called function’ takes some values from the main function, and
also returns some value back to the main function after performing its task, then it falls
under the category “Function with arguments and with return value”.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 105
`

6.3 SCOPE OF VARIABLES - LOCAL AND GLOBAL VARIABLES


Variable Scope
It is the accessibility of a variable in a given program or function.
If you live in an apartment building, you have a key that allows access to only your
apartment. The owner/manager of the apartment may have a master key that allows
access to all apartments.
A similar concept applies to
variables in C. Variable
scope refers to the accessibility of
a variable in a given program or
function.
For example, a variable may only
be available within a specific
function (your apartment key), or it
may be available to the entire C
program (the shared master key).
We can relate the apartment keys to local variables in programming language because
they only work in that apartment. The local variables are specific to a function.
The global variables refer to variables that the entire program has access to.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 106
`

Global Variables are declared outside the main() function in C. They can be accessed
or used in any function of the program.

Local Variables are declared inside a function and can be used only inside that function.
It is possible to have local variables with the same name but in different functions.
Though the name is the same, since they are declared in different functions, they are
not the same. Its like two people with the same name.

The Scope of a variable refers to where is a variable visible or accessible.

Example:
#include<stdio.h>
int b=20; // global variable accessable anywhere in the program
void main()
{
int a=10; //local to the function main() & is accessible only within this main()
void sub_fun(); //Function declaration
printf("The value of local variable 'a' in main function is %d",a);
printf("\n The value of global variable 'b' is %d",b);
sub_fun(); //call the function
getchar();
}
void sub_fun()
{
int a=50; //local to the function sub_fun accessible only within this sub_fun()
printf("\n\nThe value of local variable 'a' in sub_fun is %d",a);
printf("\n The value of global variable 'b' is %d",b);
}
Output:

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 107
`

6.4 RECURSION
A function which calls itself is called as Recursive function.
For example, 3! (3 factorial) can be calculated as 3! = 3*2*1

Let us first see the factorial of a number using ordinary function call process.
void main( )
{
int a, fact ;
printf ("\nEnter any number: " ) ;
scanf ("%d", &a) ;
fact = factorial (a) ;
printf ("Factorial value = %d", fact) ;
getchar();
}
factorial (int x)
{
int f = 1, i ;
for ( i = x ; i >= 1 ; i-- )
f = f * i;
return (f);
}
Here is the output...
Enter any number 3
Factorial value = 6
(Go through the logic of the program and understand it first, then only we can
understand the recursive function)

The same 3! can be calculated as 3!=3*2!


This can be implemented by using recursive function as follows:
void main( )
{
int a, fact ;
printf ( "\nEnter any number " ) ;
scanf ( "%d", &a ) ;
fact = rec ( a ) ;
printf ( "Factorial value = %d", fact ) ;
getchar();
}

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 108
`

rec ( int x )
{
int f ;
if ( x == 1 )
return ( 1 ) ;
else
f = x * rec ( x - 1 ) ;
return ( f ) ;
}
Here is the output for the program
Enter any number 3
Factorial value = 6

Various Input Situations


Let us see the execution when the number entered through scanf( ) is 1. The
value of a = 1 is copied into x when rec(a) function is called. In rec(a) function the
condition if ( x == 1 ) is satisfied and hence 1 (which indeed is the value of 1 factorial) is
returned through the return statement.
Let us see the execution when the number entered through scanf( ) is 2. The if (
x == 1 ) test fails, so we reach the statement,
f = x * rec ( x - 1 ) ;
the fuction rec(a) calls itself. This is recursion. How do we handle the expression x * rec
( x - 1 )? We multiply x by rec ( x - 1 ). Since the current value of x is 2, it is same as
saying that we must calculate the value (2 * rec ( 1 )). We know that the value returned
by rec ( 1 ) is 1, so the expression reduces to (2 * 1), or simply 2. Thus the statement,
x * rec ( x - 1 ) ;
evaluates to 2, which is stored in the variable f, and is returned to main( ), where it is
duly printed as
Factorial value = 2
Assume that the number entered through scanf( ) is 3. Using the flow chart given
below, let’s visualize what exactly happens when the recursive function rec( ) gets
called. Go through the flowchart carefully.
The first time when rec( ) is called from main( ), x = 3. Since x is not equal to 1,
the if block is skipped and rec( ) is called again with the argument ( x – 1 ), i.e. 2. This is
a recursive call. Since x is still not equal to 1, rec( ) is called yet another time, with

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 109
`

argument (2 - 1). This time as x is 1, control goes back to previous rec( ) with the value
1, and f is evaluated as 2.
Similarly, each rec( ) evaluates its f from the returned value, and finally 6 is
returned to main( ). The sequence would be grasped better by following the arrows
shown in the flow chart.

Caution: If we fail to handle recursive function properly, it may lead to infinite loop.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 110
`

6.5 STRING FUNCTIONS


Standard Library String Functions:
Every C Compiler, has a large set of string handling library functions. The table lists the
most commonly used string functions and their purpose. Whenever we use these string
functions in our C Program, we must include the header file, string.h.

String
Description
functions
strcat ( ) Concatenates str2 at the end of str1
strncat ( ) Appends a portion of string to another
strcpy ( ) Copies str2 into str1
strncpy ( ) Copies given number of characters of one string to another
strlen ( ) Gives the length of str1
Returns 0 if str1 is same as str2. Returns <0 if strl < str2. Returns
strcmp ( )
>0 if str1 > str2
Same as strcmp() function. But, this function negotiates case. “A”
strcmpi ( )
and “a” are treated as same.
strchr ( ) Returns pointer to first occurrence of char in str1
strrchr ( ) last occurrence of given character in a string is found
strstr ( ) Returns pointer to first occurrence of str2 in str1
strrstr ( ) Returns pointer to last occurrence of str2 in str1
strdup ( ) Duplicates the string
strlwr ( ) Converts string to lowercase
strupr ( ) Converts string to uppercase
strrev ( ) Reverses the given string
strset ( ) Sets all character in a string to given character
strnset ( ) It sets the portion of characters in a string to given character
strtok ( ) Tokenizing given string using delimiter

Usage of String functions in a program:

//Palindrome checking
//Checking whether the reverse of a word is the same as that of the original word
entered.
// AMMA – read from the reverse, it is the same! Right?? So, AMMA is palindrome.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 111
`

#include<stdio.h>
#include<string.h>
void main()
{
char a[20], b[20];
printf("enter a string");
scanf("%s",a);
strcpy(b, a); // copy string from a to b
strrev(b); // reverse the string
if(strcmp(a, b)==0) // compare a and b. If same then result is 0.
{
printf("%s is palindrome",a);
}
else
{
printf("%s is not a palindrome",a);
}
getchar();
}
Output:

The above program has used, the string functions such as strcpy(),strrev() and strcmp().
strcpy(b,a) – String copy - the string present in ‘a’ is copied to ‘b’
strrev(b) – String reverse – the string present in b is reversed
strcmp(a,b) – String compare – the two strings a & b are compared. If both the strings
are matched correctly by all means, even considering the upper & lower case matches,
this function will return 0, otherwise it will return an integer value.
See the above output, it shows MADAM is palindrome. Now check this output given
below:

It shows, MaDAm is not palindrome. This shows clearly that strcmp() compares for
exact matches and it is case sensitive for comparison.
(Try this program in other methods… You Can do it!)

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 112
`

Time to recall & Test yourself!

1. Every called function must contain a return statement – (T/F)


2. A function may contain more than one return statements – (T/F)
3. In C, same name can be used for different functions without any conflict – (T/F)
4. A function may be called more than once from any other function – (T/F)
5. The same variable names can be used in different functions without any conflict –
(T/F)
6. Write a recursive function to print the Fibonacci series.
1 1 2 3 5 8 13……
7. Write a C program to enter the names of your classmates in random order and sort
their names in alphabetical order.
8. char fruit[10] = “banana”. Use suitable string function and write the statement to
reverse the string .
9. I have used string function strcmp() to compare two strings. Which header file
should I include in my program?
10. A function calls itself is. What are such functions called as?
11. The value retured to the main function from the called function is 8.9, what would
be the return type of the called function?
12. What is the return type of main() function?
13. int x = strncmp(“Hello”,”HELLO”,3); What value is stored in x?
14. What will be the output of the following program?
int main()
{
char a[10]=”Hello”;
strset(a,’$’);
printf(“%s”,a);
getchar();
}
15.________ is a self contained block of statements, which is used to perform a
particular task
16. Which string function is used for finding the length of a string?
17. Which string function is used for comparing the 2 strings?
18. What is the output of the following program?
float one=10;
int main()
{
float two=20;
update();
printf(“%d %d”, one, two);
}
Update()

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 113
`

{
float two = 30;
one++;
}
19.Differentiate Global and Local Variables.
20. What will be the output of the following code ?
main()
{
int i;
printf(“%d”,scanf(“%d”,&i)); // value 10 is given as input here
}
21. What will be the output of the following code ?
output()
{
printf(“%p”,output);
}
a. Error b. Some address c. infinite loop d. garbage value
22. Determine the output.
main()
{
int i = abc(10);
printf(“%d”, --i);
}
int abc(int i)
{
return(i++);
}
23. Determine the output.
main()
{
float t = 2;
switch(t)
{
case 2: printf("Hi");
default: printf("Hello");
}
}
a. Hi b. HiHello c. Hello d. Error

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 114
`

UNIT - 7
POINTERS
7.1 POINTER - DECLARATION & DEFINITION
Consider the declaration,
int a=10;
This declaration tells the compiler,
a. a is the name of the memory location
b. This memory location is allocated with 2 bytes of memory, capable of storing only
integer data types.
c. The memory location a is assigned with a value 10.

Let us assume the


memory is allocated at
memory address 65528.
Let us interpret with the
following picture.

This address 65528 is


allocated dynamically
depeneding on which part
of memory is available at
that time. Every time we
execute the program, the computer may allocate different memory location for this
variable.
Let us now try to print this address through our program. When we try to print the
address, we need to use the format specifier %u, since 65528 is unsigned integer.
#include<stdio.h>
void main()
{
int a=10;
printf(“\n The value of a is : %d”,a);
printf(“\n The address of a is :%u”,&a);
getchar();
}
Output:
The value of a is : 10
The address of a is : 65528

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 115
`

Have a keen look into the printf() statement, which printed the address of a. We have
used & symbol, along with the variable name ‘a’, inorder to print the address. We were
usually using this & symbol in scanf() statements only.

There is an operator in C “*”, which is called as “Value at address” operator. It gives


the value stored at a particular address. The “value at address” operator is also called
as “indirection operator”
Let’s see the usage of “*” operator in a program.
#include<stdio.h>
void main()
{
int a=10;
printf(“\n The value of a is : %d”,a); // value in a
printf(“\n The address of a is :%u”,&a); // address of a
printf(“\n The value of a is :%d”,*(&a)); // Content at address
getchar();
}
Output:
The value of a is : 10
The address of a is : 65528
The value of a is: 10

In the above program, the value of a is printed in two ways.


a. By simply specifying the name of the memory location
b. By using *(&a) // content at address of a gives the address of the variable a
Suppose, we want to store or assign this address in another variable, like,
p=&a;

This is not possible, since address cannot be


stored in ordinary integer variables, since
compiler need to provide proper space in the
memory to store address.
We’ll also interpret with a picture, how this
statement p=&a; will look in the memory.
Also, simply we cannot use p in our program without declaring it. So, C has a special
concept to store the address of variable, which is called as Pointer.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 116
`

Definition:
What is a pointer?
Pointer is a variable, which holds the address of another variable

Watch & Learn : “Pointer Introduction”


Click the following links or else just select the links, copy & paste the links in your browser
https://youtu.be/BXY4dD6vaIE
https://youtu.be/v9FTFkxbnYQ

Declaration of Pointer:
datatype *pointervariable_name;
int *p;
Now, we’ll go by the meaning of * operator. It stands for “Value at address”. Thus int
*p; would mean, the value at the address contained in p is an int.
Let’s see one example, demonstrating this concept.

#include<stdio.h>
void main()
{
int a=10;
int *p; // It is a pointer to a variable of type int
p = &a; //store the address of a in pointer p
printf(“\n Address of a is : %u”,&a);
printf(“\n Address of a is : %u”,p);
printf(“\n Address of p is : %u”,&p);
printf(“\n The value of p is: %u”,p);
printf(“\n The value of a is: %d”,a);
printf(“\n The value of a is: %d”,*(&a));
printf(“\n The value of a is: %u”,*p);
getchar();
}
Output:
Address of a is : 65528
Address of a is : 65528
Address of p is : 65524
The value of p is : 65528
The value of a is : 10
The value of a is : 10
The value of a is : 10

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 117
`

For our Understanding:


int *p;
char *c;
float *f;

The above declarations say that, *p,*c *f are pointer variables, which are capable of
holding addresses, which does not mean that these addresses are int, char ,float data
types. They are always whole numbers.

The declaration int *p, says, *p is the pointer variable which points to the address,
having integer value.

The declaration char *c, says, *c is the pointer which points to the address, having
character value.
Similarly, The declaration float *f, says, *f is the pointer which points to the address,
having floating point/ decimal value.

The concept of Pointers can be further extended, in a way, we can even create pointers
to point another pointer variable. We know that pointer is a variable that contains the
address of another variable. Now, this variable itself might be another pointer. Thus we
have now a pointer that contains another pointer’s address.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 118
`

We’ll understand it with the help of the following program.


#include<stdio.h>
void main()
{
int a,*p,**ptr; // ptr is the pointer to the integer pointer p
p=&a; // address of a is assigned to the pointer p
ptr=&p; // address of pointer p is assigned to pointer ptr
printf(“\n Address of a is : %u”,&a);
printf(“\n Address of a is : %u”,p);
printf(“\n Address of a is : %u”,*ptr);
printf(“\n Address of p is : %u”,&p);
printf(“\n Address of p is : %u”,ptr);
printf(“\n Address of ptr is : %u”,&ptr);
printf(“\n The value of p is: %u”,p);
printf(“\n The value of ptr is: %u”,ptr);
printf(“\n The value of a is: %d”,a);
printf(“\n The value of a is: %d”,*(&a));
printf(“\n The value of a is: %u”,*p);
printf(“\n The value of a is: %u”,**ptr);
getchar();
}
Output:
Address of a is : 65528
Address of a is : 65528
Address of a is : 65528
Address of p is : 65524
Address of p is : 65524
Address of ptr is : 65520
The value of p is : 65528
The value of ptr is :65520
The value of a is : 10
The value of a is : 10
The value of a is : 10
The value of a is : 10

The above concept of making a pointer to point to another pointer is called as “Pointer
to Pointer”. Like this we can extend pointing to any number of pointers point to one
another.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 119
`

Watch & Learn : “Pointer to Pointer”


Click the following link or else just select the link, copy & paste the link in your browser
https://youtu.be/oODmPKjczg0

7.2 POINTER & ARRAYS


Pointer & One dimensional Array:

Array is a group of elements of same data type which are stored in contiguous memory
locations. We can print the array elements one by one with the help of their index
numbers, say a[0], a[1], a[2], etc. Consider an integer array ‘a’, with the base address,
the first element’s address as 1001, the second element’s address as 1003, the third
element’s address as 1005 etc., When we make a pointer ‘ptr’ to point to this array’s
base address, we should also take steps to move the pointer to the next addresses in
order to navigate across the elements of the array.
Let us see, how this is possible, making a pointer to point an array.

When an array is declared, compiler allocates sufficient amount of memory to contain


all the elements of the array. Base address gives location of the first element of the
array. An array name is a constant pointer to the first element of the array. Therefore,
in the declaration –
int a[5];

The array name ‘a’ is a pointer to &a[0], the address of the first element of the array
‘a’. Thus, the following program fragment assigns ptr as the address of the first
element of ‘a’.
int a[5];
int *ptr;
ptr = a; // this statement is equivalent to ptr=&a[0];

Therefore array names themselves are constant pointers. Hence, *(a + 4) is equivalent
to a[4] ie 5th element data of array ‘a’.

Once you store the address of the first element in 'ptr', you can access the array

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 120
`

elements using *ptr, *(ptr+1), *(ptr+2) and so on. Given below is the example to show
all the concepts discussed above.

Program:
#include <stdio.h>
void main ()
{
int a[5] = {2, 10, 5, 7, 9}; // an array with 5 elements
int *ptr;
int i;
ptr = a; // this statement is equivalent to ptr=&a[0];
printf( "Array values using pointer\n"); // output each array element's value
for ( i = 0; i < 5; i++ )
{
printf("*(ptr + %d) : %d\t", i, *(ptr + i) );
}
printf( "Array values using ‘a’ as address\n");
for ( i = 0; i < 5; i++ )
{
printf("*(a + %d) : %d\t", i, *(a + i) );
}
getchar();
}
Output:

The above program can even be re-written and print the elements of array, just by
incrementing the pointer as follows:
void main( )
{
int a[5] = {2,10,5,7,9} ;
int i, *ptr ;
ptr = &a[0] ; /* assign address of zeroth element */

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 121
`

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


{
printf ( "\naddress = %u ", ptr ) ;
printf ( "\nelement = %d", *ptr ) ;
ptr++ ; /* increment pointer to point to next location */
}
getchar();
}
Output:

Note :
a. Accessing array elements by pointers is always faster than accessing them by
subscripts.
b. Consider an array, int num[ ] = { 24, 34, 12, 44, 56, 17 } ;
We also know that on mentioning the name of the array we get its base address. Thus,
by saying *num we would be able to refer to the zeroth element of the array, that is,
24. One can easily see that *num and *( num + 0 ) both refer to 24.
Similarly, by saying *( num + 1 ) we can refer the first element of the array, that is, 34.
In fact, this is what the C compiler does internally. When we say, num[i], the C compiler
internally converts it to *( num + i ).
This means that all the following notations are same:
num[i]
*( num + i )
*( i + num )
i[num]

Pointer & Two dimensional Array


Each row of a two-dimensional array can be thought of as a one-dimensional pointer
array. This is a very important fact if we wish to access array elements of a two-
dimensional array using pointers.
Thus, the declaration,

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 122
`

int s[5][2] ;
can be thought of as setting up an array of 5 rows, each of which is a one-dimensional
array containing 2 integers. We refer to an element of a one-dimensional array using a
single subscript.
Similarly, if we can imagine ‘s’ to be a one-dimensional array then we can refer to its
zeroth element as s[0], the next element as s[1] and so on. More specifically, s[0] gives
the address of the zero’th one-dimensional array, s[1] gives the address of the first one-
dimensional array and so on.
The compiler knows that s is an array
containing 5 one-dimensional arrays, each
containing 2 integers. Each one-
dimensional array occupies 4 bytes (two
bytes for each integer). These one-
dimensional arrays are placed as shown in
the figure. (zeroth 1-D array followed by
first 1-D array, etc.).

We know that the expressions s[0] and s[1] would yield the addresses of the zeroth and
first one-dimensional array respectively. Now, we have been able to reach each one-
dimensional array. Suppose we want to refer to the element s[2][1] using pointers, (s[2]
+ 1 ) would give the address s[2][1]. And the value at this address can be obtained by
using the value at address operator, saying *(s[2] + 1 ).

We have already studied while learning one-dimensional arrays (under the heading
‘Note’ – Point b), that num[i] is same as *( num + i ). Similarly, *( s[2] + 1 ) is same as,
*( *( s + 2 ) + 1 ).
Thus, all the following expressions refer to the same element,
s[2][1]
* ( s[2] + 1 )
*(*(s+2)+1)
Program:
void main( )
{
int s[5][2] = { { 12, 56 }, { 12, 33 }, { 14, 80 }, { 13, 78 } , { 32, 64 } } ;
int i, j;
for ( i = 0 ; i <= 3 ; i++ )
{

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 123
`

printf ( "\n" ) ;
for ( j = 0 ; j <= 1 ; j++ )
printf ( "%d ", *( *( s + i ) + j ) ) ;
}
getchar();
}
Output:

The above program can be even written, a pointer to point to a 2Dimensional array as
follows:
Program:
#include <stdio.h>
void main( )
{
int s[5][2] = { { 12, 56 }, { 12, 33 }, { 14, 80 }, { 13, 78 } , { 32, 64 } } ;
int i, j ,*ptr;
for ( i = 0 ; i <= 3 ; i++ )
{
printf ( "\n" ) ;
ptr=s[i]; // pointer pointing to the i’th row 1’st element
for ( j = 0 ; j <= 1 ; j++ )
printf ( "%d ", *( ptr+j) ) ;
/* printing value of 2D array using pointer just making pointer to move horizontally
across the rows*/
}
getchar();
}
Output:

Array of Pointers
The way there can be an array of integers, floats etc, similarly there can be an array of
pointers since pointer variable contains an address, an array of pointers would be
nothing but an array of addresses of isolated variables or addresses of array elements
or any other addresses. All rules that apply to an ordinary array apply to the array of
pointers as well.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 124
`

This is an example using array of string pointers


#include <stdio.h>
int main()
{
char *fruit[] = { "mango", "banana", "pear", "apple", "orange", “grape", "blueberry" };
int x;
for(x=0;x<7;x++)
puts(fruit[x]);
getchar();
return(0);
}

The following is an example for array of integer pointers


#include <stdio.h>
void main()
{
int *arr[4]; /*array of integer pointers*/
int i=31, j=5, h=19, k=7, l, m;
arr[0] = &i ;
arr[1] = &j;
arr[2] = &h;
arr[3] = &k;
for( m = 0; m <= 3; m++)
printf("%d", *( arr[m] ));
}

7.3 CALL BY VALUE & CALL BY REFERENCE


Earlier we have studied use of functions and calling of functions. There are two ways
to call a function.
a. Call by value
b. Call be reference.

Call by Value

Whenever we called a function and passed something to it we have always passed the
‘values’ of variables to the called function. Such function calls are called ‘call by value’.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 125
`

By this what we mean is, on calling a function we are passing values of the variables.
The examples of call by value are shown below:
sum( a, b, c ) ;
function1( a ) ;

Call by Reference

We have also learnt that variables are stored somewhere in memory. So instead of
passing the value of a variable, can we not pass the location / address of the variable
to a function? If we were able to do so it would become a ‘call by reference’. The
examples of call by reference are shown below:
sum( &a, &b, &c ) ;
function1( &a ) ;

In short, passing values to a called function is “Call by Value” and passing address to
a called function is “Call by Reference”

The Call by value and Call by reference can be easily understood, by executing the
swapping of 2 numbers program.
//Call by Value Program
#include<stdio.h>
void main()
{
int a=10, b=20;
void swap(int, int); ///Function declaration
printf(“The values in main before swapping: a=%d, b=%d”,a, b);
swap(a, b); //call by values
printf(“The values in main after swapping: a=%d, b=%d”,a, b);
getchar();
}
void swap(int c, int d) // value of c==a and d = b from main function
{
int temp;
temp=c;
c = d;
d=temp;
printf(“The values in swap: c=%d, d=%d”, c, d );
}

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 126
`

Output:
The values in main before swapping: a=10, b=20
The values in swap: c=20, d=10
The values in main after swapping: a=10, b=20

You will find that the actual values in main fuction have not changed. That is
because the values of a and b were copied in to c and d. In the swap(c, d) function c
and d were swapped.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 127
`

In Call by value, the actual values of a & b are not swapped or interchanged. The
swapping of values happened only inside the called function and not on the actual
values.
//Call by Reference Program
#include<stdio.h>
void main()
{
int a=10, b=20;
void swap(int *,int *); // Funcion declaration
printf(“The values in main before swapping: a=%d, b=%d”,a, b);
swap(&a, &b); // pass the addresses of a and b
printf(“The values in main after swapping: a=%d, b=%d”,a, b);
getchar();
}
void swap(int *c,int *d) //receive addresses of a and b into c and d
{
int temp;
temp=*c;
*c=*d;
*d=temp;
printf(“The values in swap: c=%d, d=%d”, *c, *d);
}
Output:
The values in main before swapping: a=10, b=20
The values in swap: c=20, d=10
The values in main after swapping: a=20, b=10

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 128
`

In Call by reference, the actual values of a & b are swapped/interchanged even though
there is no returning of values from the called function. This is because, the changes
happened to the values pointed by the addresses.
Watch & Learn : “Call by Value & Call by Reference”
Click the following link or else just select the link, copy & paste the link in your browser
https://youtu.be/kCiNYzHuIX8

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 129
`

7.4 WRITING TO AND READING FROM FILE

Many times we want the data to be stored in a file for future reference. Whenever the
data is displayed, on the output screen, the output is temporarily available. So, it is
necessary to store the data, so that it can be viewed or retrieved fully or partly later.
Obviously, to store it permanently, we need to store and access data from the disk.

Before we start doing file input/output let us first find out how data is organized on the
disk. All data stored on the disk is in binary form. How this binary data is stored on the
disk varies from one OS to another. However, this does not affect the C programmer
since he has to use only the library functions written for the particular OS to be able to
perform input/output. This is illustrated as follows:

File Operations
There are different operations that can be carried out on a file. These are:
a. Creation of a new file
b. Opening an existing file
c. Reading from a file
d. Writing to a file
e. Moving to a specific location in a file (seeking)
f. Closing a file

In this chapter, we are going to discuss on reading data from a file and writing data to
a file.

Let us explore reading and writing operations by executing few examples.

Example 1:
// Reading a data from a file on the disk, and displaying on the output screen.
include <stdio.h>
void main( )
{
FILE *fp ; //File pointer or file handle

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 130
`

char ch;
fp = fopen ( "Struct_C_pgm.c", "r" ) ; // opening a file
if (fp==NULL) // unable to open the file
{
puts("Sorry! cannot open the file");
getchar();
exit(1);
}
while ( 1 ) //infinite loop
{
ch = fgetc ( fp ) ; // reads file contents from the file
if ( ch == EOF ) // if the “End of File” reached, break reading operation.
break ;
printf ( "%c", ch ) ;
}
fclose ( fp ) ;
getchar();
}
Output:
On executing the above program, the contents of the Struct_C_pgm.c, will be displayed
on the screen as follows:

Explanation of the file functions used in the above program:

We use the FILE pointer to navigate through the file. It is like a handle.
fopen() – to open a file
Before we read (or) write information from (or) to a file on a disk, it must be opened.
To open a file, fopen() function is used. In the above program, we have opened the file,

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 131
`

in “r” mode, read mode. Note that this r is not a character, it is enclosed within double
quotes, hence it is a string. fopen() performs 3 tasks: They are:
a. It searches on the disk (in the
given file path), the file to be
opened.
b. Then it loads the file from the disk
into a place in memory called
buffer.
c. It sets up a character pointer that
points to the first character of the
buffer.
The OS copies the file from disk in to RAM. This is called buffer. It will read the contents
of the file into the buffer while opening the file and then read the file character by
character from the buffer rather than from the disk. Same operation is followed for
writing also.
There are different mode of opening a file. They are:

File Open Operations


Action Done
Mode Possible
"r" Searches file. If the file is opened successfully Operations possible
fopen( ), loads it into memory and sets up a pointer – read from file.
pointingy4a to the first character in it. If the file
cannot be opened fopen( ) returns NULL.

"w" Searches file. If the file exists, its contents are Operations possible
overwritten. If the file doesn’t exist, a new file is – write to the file.
created. Returns NULL, if unable to open file.

"a" Searches file. If the file is opened successfully Operations possible


fopen( ) loads it into memory and sets up a pointer - add new contents
that points to the last character in it. If the file at the end of file.
doesn’t exist, a new file is created. Returns NULL,
if unable to open file.

"r+" Searches file. If is opened successfully fopen( ) Operations possible


loads it into memory and sets up a pointer which - read existing
points to the first character in it. Returns NULL, if content, write new
unable to open the file. content, modify
existing contents of
the file.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 132
`

"w+" Searches file. If the file exists, its contents are Operations possible
overwritten. If the file doesn’t exist a new file is - write new
created. Returns NULL, if unable to open file. contents, read them
back and modify
existing contents of
the file.
"a+" Searches file. If the file is opened successfully Operations possible
fopen( ) loads it into memory and sets up a pointer - read existing
which points to the first character in it. If the file content, append
doesn’t exist, a new file is created. Returns NULL, new contents to end
if unable to open file. of file. Cannot
modify existing
contents.

All the information, like mode of opening, size of file, place in the file from where the
next read operation would be performed, will be gathered by fopen() in a structure
called FILE. The definition of FILE structure is in stdio.h header file. fopen() returns the
address of this structure, which we have collected in the structure pointer called fp.

There is a possibility that when we try to open a file using the function fopen( ), the file
may not be opened. While opening the file in “r” mode, this may happen because the
file being opened may not be present on the disk. Similarly, while opening the file for
writing, fopen( ) may fail due to a number of reasons, like, disk space may be insufficient
to open a new file, or the disk may be write protected or the disk is damaged and so
on. If the file opening fails due to any of the several reasons mentioned above, the
fopen( ) function returns a value NULL.

fgetc() – to read the file contents


To read the file’s contents from memory the fgetc( ) function is used.
ch = fgetc ( fp ) ;

fgetc( ) reads the character from the current pointer position, advances the pointer
position so that it now points to the next character, and returns the character that is
read, which we collect in the variable ch. Note that once the file has been opened, we
no longer refer to the file by its name, but through the file pointer fp.

We have used the function fgetc( ) within an infinite while loop. There has to be a way
to break out of this while. When shall we break out... the moment we reach the end of

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 133
`

file. But what is end of file? A special character, whose ASCII value is 26, signifies end
of file. This character is inserted beyond the last character in the file, when it is created.

While reading from the file, when fgetc( ) encounters this special character, instead of
returning the character that it has read, it returns the macro EOF. The EOF macro has
been defined in the file “stdio.h”. In place of the function fgetc( ) we could have as well
used the macro getc( ) with the same effect. In our program we go on reading each
character from the file till end of file is not met. As each character is read we display it
on the screen. Once out of the loop, we close the file.

exit()
Exit function will terminate the execution of a program. Usually, value 0 is passed to
exit() function, when the termination is normal. A non – zero indicates an abnormal
termination of the program.

fclose()
When the reading operation in the above example program is over, the file need to be
closed. This is done by fclose() function. Once we close the file, we cannot read the file
thereafter. For closing a file, we didn’t use the filename, we have used the file pointer
fp. On closing the file, the buffer associated with the file is also removed from the
memory.
Writing to a File: Copying the content of one file to another file.
As we have learnt through a program for reading a file, now we’ll learn to copy/write
the content of one file to another file through a program.
#include <stdio.h>
void main( )
{
FILE *fs, *ft ; // declare file pointer
char ch ;
fs = fopen ( "pointer1.c", "r" ) ; // open file for reading
if ( fs == NULL )
{
puts ( "Cannot open source file" ) ;
getchar();
exit( ) ;
}
ft = fopen ( "forsem.c", "w" ) ; //open for writing
if ( ft == NULL )
{
puts ( "Cannot open target file" ) ;
fclose ( fs ) ;

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 134
`

getchar();
exit( ) ;
}
while ( 1 )
{
ch = fgetc ( fs ) ; //read character from file
if ( ch == EOF )
break ;
else
fputc ( ch, ft ) ; // write in to file
}
fclose ( fs ) ;
fclose ( ft ) ;
printf("File copied... Go and open the file & see");
getchar();
}
Explanation of the file function used in the above program:
fputc() – to write the contents to a file.

The fputc( ) function is similar to the putch( ) function, in the sense that both output
characters. However, putch( ) function always writes to the VDU, whereas, fputc( )
writes to the file. Which file? The file signified by file pointer ft. The writing process
continues till all characters from the source file have been written to the target file,
following which the while loop terminates.

Note: This file copy program is capable of copying only text files.

Program to Read Strings from the keyboard & writing them to a file:
#include <stdio.h>
void main( )
{
FILE *fp ;
char s[80] ;
fp = fopen ( "NTTF.TXT", "w" ) ;
if ( fp == NULL )
{
puts ( "Cannot open file" ) ;
getchar();
exit( ) ;
}
printf ( "\nEnter a few lines of text:\n" ) ;
while ( strlen ( gets ( s ) ) > 0 ) //press enter twice to terminate
{

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 135
`

fputs ( s, fp ) ;
fputs ( "\n", fp ) ;
}
fclose ( fp ) ;
printf("open the file and see the contents");
getchar();
}
Output:

Note that each string is terminated by hitting enter. To terminate the execution of the
program, hit enter at the beginning of a line. This creates a string of zero length, which
the program recognizes as the signal to close the file and exit.
We have set up a character array to receive the string; the fputs( ) function then writes
the contents of the array to the disk. Since fputs( ) does not automatically add a newline
character to the end of the string, we must do this explicitly to make it easier to read
the string back from the file.

A new file is created with the file name NTTF.txt

The contents we typed through keyboard are written on the file “NTTF.txt”

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 136
`

Program to read the string from the disk file:

/* Reads strings from the file and displays them on screen */

#include <stdio.h>
void main( )
{
FILE *fp ;
char s[100] ;
fp = fopen ( "NTTF.TXT", "r" ) ;
if ( fp == NULL )
{
puts ( "Cannot open file" ) ;
getchar();
exit( ) ;
}
while ( fgets ( s, 99, fp ) != NULL )
printf ( "%s" , s ) ;
fclose ( fp ) ;
getchar();
}

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 137
`

Output:

The function fgets( ) takes three arguments.


a. The first is the address where the string is stored
b. The second is the maximum length of the string. This argument prevents fgets( ) from
reading in too long a string and overflowing the array.
c. The third argument, as usual, is the pointer to the structure FILE.
When all the lines from the file have been read, we attempt to read one more line, in
which case fgets( ) returns a NULL.

7.5 C- Preprocessor, Memory Allocation in C


C- Preprocessor
 Before a C program is compiled in a compiler, source code is processed by a
program called preprocessor. This process is called preprocessing.
 Commands used in preprocessor are called preprocessor directives and they begin
with “#” symbol.

Below is the list of preprocessor directives that C programming language offers.

Preprocessor Syntax/Description
Syntax: #define
Macro This macro defines constant value and can be any of the basic
data types.

Syntax: #include <file_name>


Header file inclusion The source code of the file “file_name” is included in the main
program at the specified place.

Syntax: #ifdef, #endif, #if, #else, #ifndef


Conditional compilation Set of commands are included or excluded in source program
before compilation with respect to the condition.

Syntax: #undef, #pragma


#undef is used to undefine a defined macro variable. #Pragma is
Other directives
used to call a function before and after main function in a C
program.

A program in C language involves into different processes. Below diagram will help you
to understand all the processes that a C program comes across.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 138
`

There are 4 regions of memory which are created by a compiled C program. They are,

1. First region – This is the memory region which holds the executable code of the
program.
2. 2nd region – In this memory region, global variables are stored.
3. 3rd region – stack
4. 4th region – heap
EXAMPLE PROGRAM FOR #DEFINE, #INCLUDE PREPROCESSORS IN C LANGUAGE:

 #define – This macro defines constant value and can be any of the basic data types.
 #include <file_name> – The source code of the file “file_name” is included in the
main C program where “#include <file_name>” is mentioned.
#include <stdio.h>
#define height 100
#define number 3.14
#define letter 'A'
#define letter_sequence "ABC"
#define backslash_char '\?'
void main()

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 139
`

{
printf("value of height : %d \n", height );
printf("value of number : %f \n", number );
printf("value of letter : %c \n", letter );
printf("value of letter_sequence : %s \n", letter_sequence);
printf("value of backslash_char : %c \n", backslash_char);
}
OUTPUT:
value of height : 100
value of number : 3.140000
value of letter : A
value of letter_sequence : ABC
value of backslash_char : ?

EXAMPLE PROGRAM FOR CONDITIONAL COMPILATION DIRECTIVES:


A) EXAMPLE PROGRAM FOR #IFDEF, #ELSE AND #ENDIF IN C:
 “#ifdef” directive checks whether particular macro is defined or not. If it is defined,
“If” clause statements are included in source file.
 Otherwise, “else” clause statements are included in source file for compilation and
execution.
#include <stdio.h>
#define RAJU 100
int main()
{
#ifdef RAJU
printf("RAJU is defined. So, this line will be added in " \
"this C file\n");
#else
printf("RAJU is not defined\n");
#endif
return 0;
}

OUTPUT:
RAJU is defined. So, this line will be added in this C file

B) EXAMPLE PROGRAM FOR #IFNDEF AND #ENDIF IN C:

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 140
`

 #ifndef exactly acts as reverse as #ifdef directive. If particular macro is not defined,
“If” clause statements are included in source file.
 Otherwise, else clause statements are included in source file for compilation and
execution.
#include <stdio.h>
#define RAJU 100
int main()
{
#ifndef SELVA
{
printf("SELVA is not defined. So, now we are going to " \
"define here\n");
#define SELVA 300
}
#else
printf("SELVA is already defined in the program”);

#endif
return 0;
}
OUTPUT:
SELVA is not defined. So, now we are going to define here

C) EXAMPLE PROGRAM FOR #IF, #ELSE AND #ENDIF IN C:


 “If” clause statement is included in source file if given condition is true.
 Otherwise, else clause statement is included in source file for compilation and
execution.
#include <stdio.h>
#define a 100
int main()
{
#if (a==100)
printf("This line will be added in this C file since " \
"a \= 100\n");
#else
printf("This line will be added in this C file since " \
"a is not equal to 100\n");

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 141
`

#endif
return 0;
}
OUTPUT:

This line will be added in this C file since a = 100

EXAMPLE PROGRAM FOR UNDEF IN C LANGUAGE:


This directive undefines existing macro in the program.

#include <stdio.h>
#define height 100
void main()
{
printf("First defined value for height : %d\n",height);
#undef height // undefining variable
#define height 600 // redefining the same for new value
printf("value of height after undef \& redefine:%d",height);
}
OUTPUT:
First defined value for height : 100
value of height after undef & redefine : 600

EXAMPLE PROGRAM FOR PRAGMA IN C LANGUAGE:


Pragma is used to call a function before and after main function in a C program.

#include <stdio.h>
void function1( );
void function2( );

#pragma startup function1


#pragma exit function2

int main( )
{
printf ( "\n Now we are in main function" ) ;
return 0;
}

void function1( )
{

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 142
`

printf("\nFunction1 is called before main function call");


}

void function2( )
{
printf ( "\nFunction2 is called just before end of " \
"main function" ) ;"
}
OUTPUT:
Function1 is called before main function call
Now we are in main function
Function2 is called just before end of main function
MORE ON PRAGMA DIRECTIVE IN C LANGUAGE:

Pragma command Description


#Pragma startup This directive executes function named
<function_name_1> “function_name_1” before

#Pragma exit This directive executes function named


<function_name_2> “function_name_2” just before termination of the
program.
#pragma warn – rvl If function doesn’t return a value, then warnings are
suppressed by this directive while compiling.

#pragma warn – par If function doesn’t use passed function parameter , then
warnings are suppressed

#pragma warn – rch If a non reachable code is written inside a program, such
warnings are suppressed by this directive.
Watch & Learn : “Preprocessors”
Click the following link or else just select the link, copy & paste the link in your browser
https://youtu.be/JZkPEl8JjZo
Memory Allocation in C
In this you'll learn to dynamically allocate memory in your C program using standard
library functions: malloc(), calloc(), free() and realloc().
As you know, an array is a collection of a fixed number of values. Once the size of an
array is declared, you cannot change it.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 143
`

Sometimes the size of the array you declared may be insufficient. To solve this issue, you
can allocate memory manually during run-time. This is known as dynamic memory
allocation in C programming.
To allocate memory dynamically, library functions used are malloc(), calloc(),
realloc() and free() are used.
These functions are defined in the <stdlib.h> header file.
malloc()
The name "malloc" stands for memory allocation.
The malloc() function reserves a block of memory of the specified number of bytes.
And, it returns a pointer of void which can be casted into pointers of any form.
Syntax of malloc()
ptr = (castType*) malloc(size);
Example
ptr = (float*) malloc(100 * sizeof(float));
The above statement allocates 400 bytes of memory. It's because the size of float is 4
bytes. And, the pointer ptr holds the address of the first byte in the allocated memory.
The expression results in a NULL pointer if the memory cannot be allocated.
Watch & Learn : “malloc() ”
Click the following link or else just select the link, copy & paste the link in your browser
https://youtu.be/SuBch2MZpZM

calloc()
The name "calloc" stands for contiguous allocation.
The malloc() function allocates memory and leaves the memory uninitialized. Whereas,
the calloc() function allocates memory and initializes all bits to zero.
Syntax of calloc()
ptr = (castType*)calloc(n, size);
Example:
ptr = (float*) calloc(25, sizeof(float));
The above statement allocates contiguous space in memory for 25 elements of
type float.
Watch & Learn : “calloc() ”
Click the following link or else just select the link, copy & paste the link in your browser
https://youtu.be/ygBDtH3EfNc

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 144
`

free()
Dynamically allocated memory created with either calloc() or malloc() doesn't get freed
on their own. You must explicitly use free() to release the space.
Syntax of free()
free(ptr);
This statement frees the space allocated in the memory pointed by ptr.
Example 1: malloc() and free()
// Program to calculate the sum of n numbers entered by the user
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int*) malloc(n * sizeof(int));
// if memory cannot be allocated
if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}

printf("Enter elements: ");


for(i = 0; i < n; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
// deallocating the memory

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 145
`

free(ptr);
return 0;
}
Here, we have dynamically allocated the memory for n number of int.
Example 2: calloc() and free()
// Program to calculate the sum of n numbers entered by the user
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int*) calloc(n, sizeof(int));
if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}

printf("Enter elements: ");


for(i = 0; i < n; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
free(ptr);
return 0;
}

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 146
`

Realloc()
If the dynamically allocated memory is insufficient or more than required, you can
change the size of previously allocated memory using the realloc() function.
Syntax of realloc()
ptr = realloc(ptr, x);
Here, ptr is reallocated with a new size x.
Example 3: realloc()
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr, i , n1, n2;
printf("Enter size: ");
scanf("%d", &n1);
ptr = (int*) malloc(n1 * sizeof(int));
printf("Addresses of previously allocated memory: ");
for(i = 0; i < n1; ++i)
printf("%u\n",ptr + i);
printf("\nEnter the new size: ");
scanf("%d", &n2);
// rellocating the memory
ptr = realloc(ptr, n2 * sizeof(int));
printf("Addresses of newly allocated memory: ");
for(i = 0; i < n2; ++i)
printf("%u\n", ptr + i);
free(ptr);
return 0;
}
When you run the program, the output will be:
Enter size: 2
Addresses of previously allocated memory:26855472

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 147
`

26855476
Enter the new size: 4
Addresses of newly allocated memory:26855472
26855476
26855480
26855484
Watch & Learn : “relloc() ”
Click the following link or else just select the link, copy & paste the link in your browser
https://youtu.be/z-MHVnhpf9w

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 148
`

Time to recall & Test yourself!


1. What is a pointer? How will you declare a pointer?
2. __________ operator is called as “Value at Operator”
3. Value at operator is also called as ___________ operator
4. &a will print ____________ of the variable a.
a. a) Value b) address
5. *(&a) will print ____________ of the variable a.
a. a) Value b) address
6. Consider a pointer ‘ptr’, and a variable ‘b’. How will you make the pointer ‘ptr’,
point to the address of ‘b’?
7. What will be the output for the following program? (say, address of a is assumed
to be 65518, and address of p is assumed to be 65510)
void main()
{
int a=10;
int *p;
p=&a;
printf(“\n Address of a is : %u”,&a);
printf(“\n Address of a is : %u”,p);
printf(“\n Address of p is : %u”,&p);
printf(“\n The value of p is: %u”,p);
printf(“\n The value of a is: %d”,a);
printf(“\n The value of a is: %d”,*(&a));
printf(“\n The value of a is: %u”,*p);
getchar();
}
8. *(*(a+5)+2) represents the value of the element present at _______ row and
_____ column of an array.
9. *(a[5]+2) represents the value of the element present at _______ row and _____
column of an array.
10.Accessing array elements by pointers is ____________ than accessing them by
subscripts.
a. a) faster b) slower c) either faster or slower d)neither slower nor faster
11.What is the output?
void main()
{
int a[5]={1, 2, 3, 4, 5},*ptr;
ptr=&a[3]
ptr++;
printf(“%d”,*ptr);
}

12.What will be the output for the following program?

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 149
`

fun(int, int);
void main()
{
int i=10; j=20;
fun(i, j);
printff(“\n i=%d, j=%d”,i, j);
}
fun(int i, int j)
{
i=i*I;
j=j*j;
}
13.What will be the output for the following program?
fun(int *, int *);
void main()
{
int i=10; j=20;
fun(&i, &j);
printff(“\n i=%d,j=%d”,i,j);
}
fun(int *i, int *j)
{
*i=*i * *i;
*j=*j * *j;
}
14.What will be the output for the following program?
fun(int *);
void main()
{
int i=35, *z;
z=fun(&i);
printf(“%d”,z);
}
void fun(int *m)
{
return (m+2);
}
15.What are the various modes of opening a file?
16.fp=fopen(“NTTF.txt”,”w”); if the file pointer could not locate the file “NTTF.txt”
what will happen?
17.Write a C program to count the number of charaters in a string entered through
the keyboard and write the count on the file available on the disk.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 150
`

UNIT - 8
STRUCTURE AND UNION
8.1 STRUCTURE - DECLARATION & ACCESSING STRUCTURE MEMBERS
There are certain situations, where we like to store related data under a single entity/
single name. We have already learnt one concept called “ARRAY”, earlier in UNIT 5, in
which group of elements of same data type are stored under as single name.

If suppose, we have a situation to store group of elements of different data types, we


cannot store that collection, under the concept of Array. C has another feature which
could store collection of data of different data types, as single entity, called “Structure”.

What is Structure?
Structure is a group of elements of different data types,(heterogeneous group of
elements), which are stored as a single entity, under a single name.

Take the example “Student”.A student has different


attributes such as Name (String), Reg no (Integer), Age
(Integer), Height (Decimal Value) etc., In such cases, the
different attributes can be grouped under a single entity
called “Structure”.

Syntax for Declaration of Structure:


struct struct_name
{
members of the structure
};
Example:
struct STUDENT // struct is keyword STUDENT is name of structure
{
char name[20]; // members of structure STUDENT
int reg_no;
int age;
float height;
};
struct is the keyword used to declare the structure and it is the data type for declaring
the structure. In the above example,
a. “STUDENT” is the structure name.
b. name,reg_no,age and height are the members of the structure.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 151
`

Once the new structure data type has been defined one or more variables can be
declared to be of that type. For example the structure variables s1, s2, s3 can be
declared to be of the type struct STUDENT, as,
struct STUDENT s1, s2, s3 ;
This statement sets aside space in memory. It makes available space to hold all the
elements in the structure. In this case, 28 bytes—20 single bytes for name, two bytes
for reg_no, two bytes for age and four bytes for height. These bytes are always in
adjacent memory locations.
If we so desire, we can combine the declaration of the structure type and the structure
variables in one statement.
For example:
struct STUDENT struct STUDENT
{ {
char name[20] ; char name[20] ;
int reg_no; int reg_no;
int age; int age;
float height; float height;
}; } s1, s2, s3 ;
struct STUDENT s1, s2, s3 ;

Initialisation of Structure
Like primary variables and arrays, structure variables can also be initialized where they
are declared. The format used is quite similar to that used to initiate arrays.
struct STUDENT
{
char name[20] ;
int reg_no;
int age;
float height;
};
struct STUDENT s1 = { "RANI", 7, 18, 5.3 } ;
struct STUDENT s2 = { "RAJA", 6, 17, 5.8 } ;
struct STUDENT s3 = { "BARANI", 2, 18, 5.5 } ;
Note the following points while declaring a structure type:
a. The closing brace in the structure type declaration must be followed by a
semicolon ;.
b. It is important to know that a structure type declaration does not tell the
compiler to reserve any space in memory. All a structure declaration does is, it
defines the ‘format’ of the structure.
c. Usually structure type declaration appears at the top of the source code file,
before any variables or functions are defined.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 152
`

Accessing Structure Elements


Having declared the structure type and the structure variables, let us see how the
elements of the structure can be accessed.
In arrays we can access individual elements of an array using a subscript. Structures use
a different scheme. They use a dot (.) operator. So to refer name of the structure
defined in our sample program we have to use,
s1.name
Similarly, to refer age we would use,
s1.age
Note that before the dot there must always be a structure variable and after the dot
there must always be a structure element.
Example:
#include<stdio.h>
void main( )
{
struct STUDENT
{
char name[20] ;
int reg_no;
int age;
float height;
};
struct STUDENT s1={"RANI",7,18,5.3};
struct STUDENT s2={"RAJA",8,16,5.8};
struct STUDENT s3={"BARANI",2,18,5.9};
printf ( "\nName of student1= %s", s1.name ) ; /* access element dot
operator.*/
printf ( "\nReg_no of student1= %d", s1.reg_no ) ;
printf ( "\nAge of student1= %d", s1.age) ;
printf ( "\nHeight of student1= %4.1f feet", s1.height ) ;
printf ( "\n\n\nName of student2= %s", s2.name ) ;
printf ( "\nReg_no of student2= %d", s2.reg_no ) ;
printf ( "\nAge of student2= %d", s2.age) ;
printf ( "\nHeight of student2= %4.1f feet", s2.height ) ;
printf ( "\n\n\nName of student3= %s", s3.name ) ;
printf ( "\nReg_no of student3= %d", s3.reg_no ) ;
printf ( "\nAge of student3= %d", s3.age) ;
printf ( "\nHeight of student3= %4.1f feet", s3.height ) ;
getchar();
}

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 153
`

Output:

How are Structure Elements Stored?

Whatever be the elements of a structure, they are always stored in contiguous memory
locations. (The explanation for contiguous memory locations have been already
explained in UNIT 5.)

The following program would illustrate this:


#include<stdio.h>
void main( )
{
struct STUDENT
{
char name[20] ;
int reg_no;
int age;
float height;
};
struct STUDENT s1={"RANI",7,18,5.3};
struct STUDENT s2={"RAJA",8,16,5.8};
struct STUDENT s3={"BARANI",2,18,5.9};
printf ( "\nAddress of name of student1= %u", &s1.name ) ;
printf ( "\nAddress of reg_no of student1= %u", &s1.reg_no ) ;
printf ( "\nAddress of age of student1= %u", &s1.age) ;
printf ( "\nAddress of height (in feet) of student1= %u", &s1.height ) ;

printf ( "\n\n\nAddress of name of student2= %u", &s2.name ) ;


printf ( "\nAddress of reg_no of student2= %u", &s2.reg_no ) ;
printf ( "\nAddress of age of student2= %u", &s2.age) ;
printf ( "\nAddress of height (in feet) of student2= %u", &s2.height ) ;

printf ( "\n\n\nAddress of name of student3= %u", &s3.name ) ;

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 154
`

printf ( "\nAddress of reg_no of student3= %u", &s3.reg_no ) ;


printf ( "\nAddress of age of student3= %u", &s3.age) ;
printf ( "\nAddress of height (in feet) of student3= %u", &s3.height ) ;
getchar();
}

OUTPUT:

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 155
`

Array within structure

If the element of a structure is an array, then it is “Array within the structure”. The
above examples can be considered for “Array within structure”.
struct STUDENT
{
char name[20] ; // character array within a structure
int reg_no;
int age;
float height;
};

Array of Structures:
Consider the above example. If we have 50 students in the class, we need not declare
50 variables S1, S2, ….. S50. Instead we can create array of structure. If the structure
variable itself is an array, then it is called as “Array of structures”
Example:
#include<stdio.h>
void main( )
{
struct STUDENT
{
int reg_no;
int age;
} s[3]; // Array of structure
int i;
for(i=0; i<3; i++)
{
printf("\nSTUDENT %d", i + 1);
printf("\nEnter the reg_no of student");
scanf("%d",&s[i].reg_no);
printf("Enter the age of student");
scanf("%d",&s[i].age);
}
for(i=0;i<3;i++)
{
printf("\nSTUDENT %d", i +1);
printf ( "\nReg_no of student1= %d", s[i].reg_no ) ;
printf ( "\nAge of student1= %d", s[i].age) ;
}
getchar();
}

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 156
`

Output:

Additional Feature 1: Structure within another structure:


One structure can be nested within another structure. Using this facility complex data
types can be created. The following program shows nested structures at work.
void main( )
{
struct address
{
char phone[15] ;
char city[25] ;
int pin ;
};
struct emp
{
char name[25] ;
struct address addr ; /* variable structure address created inside emp */
};
struct emp worker = { "jeru", "531046", "nagpur", 10 };
printf ( "\nname = %s phone = %s", worker.name, worker.addr.phone ) ;
printf ( "\ncity = %s pin = %d", worker.addr.city, worker.addr.pin ) ;
}
And here is the output...
name = jeru phone = 531046
city = nagpur pin = 10

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 157
`

Notice the method used to access the element of a structure that is part of another
structure. For this the dot operator is used twice, as in the expression,
worker.addr.pin worker.addr.city
We can nest a structure within a structure, within another structure, which is in still
within another structure and so on... till the time we can comprehend the structure
ourselves. Such construction however gives rise to variable names that can be
surprisingly self descriptive, for example: maruti.engine.bolt.large.qty
Additional Feature 2: Copying the elements of structure to another structure.
The values of a structure variable can be assigned to another structure variable of the
same type using the assignment operator. It is not necessary to copy the structure
elements piece-meal. Obviously, programmers prefer assignment to piece-meal
copying. This is shown in the following example.

void main( )
{
struct employee
{
char name[10] ;
int age ;
float salary ;
};
struct employee e1 = { "Sanjay", 30, 5500.50 } ;
struct employee e2, e3 ;
/* piece-meal copying */
strcpy ( e2.name, e1.name ) ;
e2.age = e1.age ;
e2.salary = e1.salary ;
/* copying all elements at one go */
e3 = e2 ;
printf ( "\n%s %d %f", e1.name, e1.age, e1.salary ) ;
printf ( "\n%s %d %f", e2.name, e2.age, e2.salary ) ;
printf ( "\n%s %d %f", e3.name, e3.age, e3.salary ) ;
getchar();
}
The output of the program would be...

Sanjay 30 5500.500000
Sanjay 30 5500.500000
Sanjay 30 5500.500000
Ability to copy the contents of all structure elements of one variable into the

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 158
`

corresponding elements of another structure variable is rather surprising, since C does


not allow assigning the contents of one array to another just by equating the two. As
we saw earlier, for copying arrays we have to copy the contents of the array element
by element.

This copying of all structure elements at one go has been possible only because the
structure elements are stored in contiguous memory locations.

8.2 UNION - DECLARATION & ACCESSING UNION MEMBERS

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.

Defining a Union

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 syntax of the union statement is as follows:
union union_name
{
members of union
} [one or more union variables];
The union_name is optional and the members of the union can be any valid
variable definition, such as int i; float f; etc. 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 Student having three members age,
height and name.
union Student
{
char name[20];
int age;
float height;
} s;
Now, a variable of Student 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

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 159
`

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, Student 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 Student
{
int age;
float height;
char name[20];
};
void main( )
{
union Student s;
printf( "Memory size occupied by data : %d\n", sizeof(s));
getchar();
}
When the above code is compiled and executed, it produces the following result −
Memory size occupied by data : 20

Accessing Union Members

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

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 160
`

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 Student
{
int age;
float height;
char name[20];
};
void main( )
{
union Student s;
s.age = 17;
s.height = 5.5;
strcpy( s.name, "RAHUL");
printf( "Name : %s\n", s.name);
printf( "Age : %d\n", s.age);
printf( "Height : %f\n", s.height);
getchar();
}
When the above code is compiled and executed, it produces the following result:

Here, we can see that the values of age and height members of union got corrupted
because the final value assigned to the variable has occupied the memory location and
this is the reason that the value of name member is getting printed very well.
Now let's look into the same example once again where we will use one variable at a
time which is the main purpose of having unions.
#include <stdio.h>
#include <string.h>
union Student
{
int age;
float height;
char name[20];
};

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 161
`

void main( )
{
union Student s;
s.age = 10;
printf( "Age : %d\n", s.age);
s.height = 5.5;
printf( "Height : %4.2f\n", s.height);
strcpy( s.name, "RAHUL");
printf( "Name : %s\n", s.name);
getchar();
}

When the above code is compiled and executed, it produces the following result.

Here, all the members are getting printed very well because one member is being used
at a time.
Difference between Structure & Union.
The main difference between Structure and Union, is the way in which memory is
allotted to them.

Structure Union
Declaration: Declaration:
struct Student union Student
{ {
int age; int age;
float height; float height;
}s; }u;
Memory Allocation: Memory Allocation:

Individual members occupy different Memory allocation of union is equal to the


memory allocations based on their size, biggest member’s size.
arranged in contiguous memory
allocations
All the members of the structure can be Only one member at a time can access the
accessed simultaneously. memory.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 162
`

Time to recall & Test yourself!


1. Define Structure.
2. How structure concept differ from the concept of array?
3. What is the size of the following structure? (execute in laptop and find its size)
struct S
{
char a[100];
double b;
int a[10];
}st;
4. Draw the memory map for the above program.
5. A structure S has two variables st1, st2. The members of S are title and page_no.
Give the statements by which you can initialize the members of this structure.
6. The members of the structure “Book” are Book_name & Author_Name. How will
you access theses members in your program, if the variable of the structure is ‘b’?
7. Ten floating point values need to be stored in the memory, Which concept will you
prefer? Array or Structure?
8. Which of the following statements are True, if in structure, I have used a statement
a.b.c=40;
a. structure c is nested within structure b
b. structure b is nested within struvture s
c. structure a is nested within structure b
d. structure a is nested within structure c
9. Define Union
10. How Union differs from Structure?
11. I have 3 union members, say int a, float b, char c. What is the size of this Union?
12. For a Union ‘U’, with a variable ‘un’, the members int a, float b and char c are
initialized as in order, as follows:
un.a = 5;
un.b = 5.5;
un.c = ’S’;
What will be the output if we try to print the members in the order
a. un.c =_______ b. un.a= _________ c. un.b=________

13. What is the error in the following code?


struct student
{

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 163
`

int no;
char name[20];
}

14. Which of the following operators can be applied on structure variables?


a. Equality comparison ( == ) b. Assignment ( = )
c. Both of the above d. None of the above

Extra Note: Structure members can be accessesed through a pointer to a structure


using  arrow operator. (Surf through the internet and apply the pointers over
structure...You can do it!)

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 164
`

UNIT – 9
C++ INTRODUCTION AND OOPS CONCEPTS
9.1 OBJECT ORIENTED PROGRAMMING PARADIGM
Right from the day when computer was invented, many programming approaches have
been tried. These techniques include
a. Modular Programming
b. Top –down Programming
c. Bottom –up Programming
d. Structured Programming
The main motivation behind these
programming inventions, was just
to bring down the complexity in
programming and the concern to
handle it, to make programming
reliable and maintainable.

With the advent of languages such


as C, structured programming
became very popular. We can
write complex programs easily
using Structured Programming. As
the programs grew larger, even the structured approach failed to show the desired
results in terms of bug (error) free, easy to maintain and reusable programs.
Object–Oriented Programming (OOP) eliminates some of the pitfalls of conventional
programming methods by incorporating the best of structured programming features
with several powerful new concepts. It is a new way of organising and developing
programs and has nothing to do with any particular language. However, not all
languages are suitable to implement the OOP concepts easily.

Procedure Oriented Programming


Characteristics:
a. Emphasis is on doing things (algorithms).
b. Large programs are divided into smaller programs known as functions.
c. Most of the functions share global data.
d. Data move from function to function.
e. Functions transform data from one form to another.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 165
`

f. Employs top-down approach in program design.

Object Oriented Programming Paradigm


Characteristics:
a. Emphasis is on data rather than procedure.
b. Programs are divided into what are known as objects.
c. Data structures are designed such that they characterise the objects.
d. Functions that operate on the data of an object are tied together in the data
structure.
e. Data is hidden and cannot be accessed
by external functions.
f. Objects may communicate with each
other through functions.
g. New data and functions can be easily
added whenever necessary.
h. Follows bottom – up approach in
program design.
Basic Concepts of OOP
a. Objects
b. Classes
c. Data Abstraction & Encapsulation
d. Inheritance
e. Polymorphism
f. Dynamic Binding
g. Message Passing

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 166
`

Class
A class in C++ is the building block, that leads to Object-Oriented programming. It is a
user-defined data type, which holds its own data members and member functions,
which can be accessed and used by creating an instance of that class. A C++ class is like
a blueprint for an object.
Example: Consider the Class of Cars. There may be many cars with different names and
brand but all of them will share some common properties like all of them will have 4
wheels, Speed Limit, Mileage range etc. So here, Car is the class and wheels, speed
limits, mileage are their properties.

a. A Class is a user defined data-type which has data members and member functions.
b. Data members are the data variables and member functions are the functions used
to manipulate these variables and together these data members and member
functions defines the properties and behavior of the objects in a Class.

c. In the above example of class Car, the data member will be speed limit, mileage etc
and member functions can be apply brakes, increase speed etc.
Thus Class is a collection of objects of similar type. Example: Mango, Apple and
Orange are the members of the class Fruit.

Objects
An Object is an instance of a Class. When a class is defined, no memory is allocated but
when it is instantiated (i.e. an object is created) memory is allocated.
The objects are the variables of the type class. Once a class is created, we can create as
many objects for that class. Each object is associated with the class with which it is
created. To use the data and access functions defined in the class, you need to create
objects.
Syntax:
ClassName ObjectName;

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 167
`

Data Abstraction & Encapsulation


The wrapping up of data and
function into a single unit
(called class) is known as
“Encapsulation”. Data is not
accessible to the outside
functions. Only the functions
which are wrapped in the class
can access it. This insulation
of the data from the direct
access by the program is
called “Data Hiding”.
Classes use the concept of
abstraction and are defined as
a list of abstract attributes
such as size, weight, cost and functions to operate on these attributes. These attributes
are called as data members. The functions that operate on these data are called
member functions.
Since the classes use the concept of data abstraction, they are known as “Abstract Data
Types”.

Inheritance
Inheritance is the process by which
objects of one class acquire the
properties of objects of another class.
It supports the concept of hierarchical
classification. Example: Class Bus, Class
Car are part of class Vehicle. So they
inherit all the properties of Vehicle
(parent) class.

Polymorphism
The literal meaning of “Polymorphism”
is the ability to take more than one
form. An operation may exhibit
different behaviours in different
instances. For example, consider the
operation of “+” (addition). For two
numbers, the operation will generate a
sum. If the 2 operands are strings, then +, will do concatenation operation. The process
of making an operator to exhibit different behaviours in different instances is known as
“Operator Overloading”.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 168
`

Similarly, a single function name can handle different operations, depending on the
type and number of arguments passed. This concept is known as “Function
Overloading”. This is similar to having different meanings for a single word.
Dynamic Binding
Binding refers to linking a procedure call, to the code to be executed, when it is called.
Dynamic Binding means that the code associated with a given procedure call is not
known until the time of the call at run time. It is associated with polymorphism and
inheritance. A function call associated with a polymorphic reference depends on the
dynamic type of that reference.
Consider a procedure Draw(). Every object has this procedure. However, unique to each
object and so the draw procedure will be defined in each class that defines the object.
At run time, the code matching the object under the current reference will be called.

Message Passing
An object oriented program consists of a set of objects that communicate with each
other. The process of message passing, involves the following steps:
a. Creating classes that define objects and their behaviour
b. Creating objects from class definitions and
c. Establishing communication among objects.
Objects communicate with one another by sending and receiving information much the
same way as people pass messages to one another. A message for an object is a request
for execution of a procedure, and
therefore will invoke a function
(Procedure) in the receiving object that
generates the desired result. Message
passing involves specifying the name of
the object, the name of the function (message) and the information to be sent.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 169
`

9.2 BENEFITS AND APPLICATIONS OF OOP


Benefits of OOP:
OOP offers several benefits to both the program designer and the user. Object
orientation contributes to the solution of many problems associated with the
development and quality of software products.
 Through inheritance, we can eliminate redundant code and extend the use of
existing classes
 We can build programs from standard working modules that communicate with one
another, rather than having to start writing the code from scratch. This leads to save
the development time and higher productivity.
 The principle of data hiding helps the programmer to build secure programs that
can be invaded by code in other parts of the program
 It is possible to have multiple instances of an object.
 It is easy to partition the work into projects based on objects.
 OO systems can be easily upgraded from small to large systems
 Message passing, will help us to easily communicate with the external systems.
 Software complexity can be easily managed

If the above benefits are to be explained in one word, & can be stated as follows:
 Re-usability
 Data redundancy
 Code Maintenance
 Security
 Design Benefits
 Better Productivity
 Easy Troubleshooting
 Polymorphism Flexibility
 Easy to solve Problems
Applications of OOP:
 Real Time Systems
 Simulation & Modelling
 Object oriented databases
 Hypertext, hypermedia and expertext
 AI and expert systems
 Neural networks and parallel programming
 Decision support and office automation systems
 CIM/CAM/CAD systems.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 170
`

9.3 STRUCTURE OF C++ PROGRAM

A typical C++ program has 4 sections. These Include Files Section


sections can be placed in separate code files
and then compiled independently or jointly. Class Declaration Section

It is common practice to organise a program Member Function Definition Section


into 3 separate files. The class declarations Main Function Program Section
are placed in a header file and the definitions
of member functions go into another file. This
approach enables the programmer to
separate the abstract specification of the
interface (class definition) from the
implementation details (member functions
definition). Finally, the main program that
uses the class is placed in a third file as well as
any other files required.
This approach is based on the concept of
“Client – Server” model. The class definition
including the member functions constitute
the server that provides services to the main
program known as client. The client uses the server through the public interface of the
class.
Example:
#include<iostream> // Header File Section. Similar to stdio.h in c.
using namespace std;
class M2A // Class Declaration
{
public: // access specifier
int a, b, c; //data member declaration
void display(); // member function declaration
void getdata() //member function definition inside the class
{
cout<<”Enter the values of a and b”; // similar to printf
cin>>a>>b; //Similar to scanf
}
}; //notice the semicolon
void M2A :: display() //member function definition outside the class
{ //Notice the :: operator to indicate member function
cout<<”a:”<<a<<”\nb:”<<b;

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 171
`

}
void main() // main function section
{
M2A obj; // object creation
obj.getdata(); // member function call
obj.display();
getchar();
}

The above program can be compiled in Turbo C++ compiler.

Turbo C++ Compiler:

Output:

Watch & Learn : “Structure of C++”


Click the following link or else just select the link, copy & paste the link in your browser
https://youtu.be/4drAhgFroKc

When you look the above program, the class declaration, looks alike of c – “Structures”.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 172
`

C Structure C++ Class


struct Student class M2A
{ {
int a; int a;
float b; float b;
}s1; void getdata();
void display();
}obj;

It looks as if the concept of C structures have been extended to C++ Class concept. But
there are lot of difference, when we compare them.
a. C Structure members can be accessed using structure variable, whereas the
members of the class are accessed using objects.
b. C structures have only data members, whereas, C++ has data members & member
functions.
c. The members of C structures are public in nature and can be accessed outside the
structure, whereas the members of C++ class are private by default and cannot be
accessed outside the class.

9.4 SPECIFYING A CLASS: DATA MEMBERS & MEMBER FUNCTIONS,


ACCESS SPECIFIERS
One of the major features of C++ is class. They provide a method of binding together
data and functions which operate on them. As we discussed above, Class is a user
defined data type, as like structures in C.
Syntax for Declaration of Class:
class Classname
{
member of the class  Data members & Member functions;
};
Example:
These data members and member
functions are declared inside class.
The data members and the member
functions are together called as the
members of the class. By default
these members are private to the
class, we cannot access these
members outside the class. Let us
now see the different Access

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 173
`

Specifiers. There are 3 Access Specifiers in C++. They are:

a. Private – The members of


the class cannot be accessed
outside the class.
b. Public – The members of the
class can be accessed even
outside the class.
c. Protected – The members
of the class can be accessed
outside the class and also
permitted to be used by the
immediate child class

Watch & Learn : “Visibility Modes


Click the following link or else just select the link, copy & paste the link in your browser
https://youtu.be/L0TfYL9l868

9.5 OBJECT CREATION AND ITS MEMORY ALLOCATION


In c++ the class variables are known as objects.
The syntax for the creation of object is as follows:
classname objectname;
In one statement we can declare more than one objects
Example:
M2A obj1, obj2; // M2A is class name, obj1, obj2 are objects of class M2A and
are of type class – M2 A.
Objects can also be created when a class is defined by placing their names immediately
after the closing braces as we do in the case of structures.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 174
`

class M2A
{
members of the class;
}obj1, obj2, obj3;
Instead of creating of 3 different objects like obj1, obj2, obj3, we can create “Array of
objects”.
class M2A
{
members of the class;
}obj[3];
Watch & Learn : “Classes and Objects”
Click the following link or else just select the link, copy & paste the link in your browser
https://youtu.be/WHj_PlkB9gk
Memory Allocation of Objects:
a. The member functions are created and placed in the memory space only once when
they are defined as a part of a class specification.
b. All the objects belonging to that class use the same member functions. Therefore,
no separate space is allocated for member functions when the objects are created.
c. Only space for member variables is allocated separately for each object. Separate
memory locations for the objects are essential, because the member variables will
hold different data values for different objects.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 175
`

9.6 ACCESSING THE CLASS MEMBERS WITH OBJECTS


The member functions can be called by using the object as follows:
object.mem_function(actual arguments);
Example : obj1.getdata(10, 20);
Note: Objects cannot access the private members of the class.
Objects can access the public members of the class.
Example:
#include<iostream>
using namespace std;
class M2A
{
int a; //by default the members are private
public:
int c, d, e;
void getdata(int c1, int d1)
{
c = c1;
d = d1;
}
void display()
{
a = 30; /* a is private data member, can be accessed only within
this class */
cout<<”a:”<<a;
cout<<”\n c:”<<c<<”\nd:”<<d;
}
};
void main()
{
M2A obj1;
obj1.getdata(10, 20); /* passing actual values as arguments to public
member function using the object.*/
obj1.display(); // calling the public member function using object
/* obj1.a=10; This assignment is not possible, a is private
Member and cannot be accessed outside class using object*/
obj1.e=100; /* possible to assign value using object, e is public member */
cout<<”\n e:”<<obj1.e; /* public member e can be accessed outside class
using the object*/
getchar();
}

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 176
`

Output:

9.7 USING SCOPE RESOLUTION OPERATOR - MEMBER FUNCTION & DATA


MEMBER ACCESS
In a class, member functions can be defined in 2 ways.
a. Inside the class definition
b. Outside the class definition

Member functions defined inside the class


Example:
#include<iostream>
using namespace std;
class M2A
{
public:
int a, b; // data members
void getdata() //member function getdata() defined inside class M2A
{
cout<<”Enter the valus of a & b”;
cin>>a>>b;
}
void display() //member function display()s defined inside class M2A
{
cout<<”The value of a is:”<<a<<endl;
cout<<”The value of b is:”<<b;
}
};
void main()
{
M2A obj;
obj.getdata();
obj.display();
getchar();
}
Member functions defined outside the class, using Scope resolution operator ::
Let us take the same example, but we’ll define the member functions outside the class.
When we define the member functions outside the class, we need to follow the
following syntax:

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 177
`

return_type classname :: function_name()


{
body of the function;
}
a. An important difference between a member function and a normal function is that a
member function incorporates a membership ‘identity label’ in the header.
b. This label tells the compiler which class the function belongs to.
c. The membership label class name :: tells the compiler that the function function
name belongs to the class class name
d. That is the scope of the function is restricted to the class name specified in the header
file
e. The symbol :: is called the scope resolution operator
Example:
#include<iostream>
using namespace std;
class M2A
{
public:
int a, b; // data members
void getdata(); //member function getdata() just declared inside
class
void display(); // member function display() just declared inside class
}; /* now we’ll define the member functions getdata() & display() outside the class using
scope resolution operator */
void M2A::getdata()
{
cout<<”Enter the valus of a & b”;
cin>>a>>b;
}
void M2A::display()
{
cout<<”The value of a is:”<<a<<endl;
cout<<”The value of b is:”<<b;
}
void main()
{
M2A obj;
obj.getdata();
obj.display();
getchar();
}

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 178
`

Note: The private member functions cannot be called by using the objects of the class.
It can be called like an ordinary function, only within the class.
Example:
#include<iostream>
using namespace std;
class M2A
{
int a, b; // private data members
void getdata(); //private member function
public:
void display();
};
/* now we’ll define member functions getdata() & display() outside the class using scope
resolution operator */
/* getdata() is a private member function, which can be defined outside the class
definition, using scope resolution operator, which makes the scope of the getdata()
function inside the class.*/
void M2A::getdata()
{
a=100;
b=200;
}
void M2A::display()
{
getdata(); /* private member function can be called like an ordinary function
call */
cout<<"The value of a is:"<<a<<endl;
cout<<"The value of b is:"<<b;
}
void main()
{
M2A obj;
//obj.getdata();  we cannot call the private member function using the object
obj.display(); // display() in turn is calling getdata()
getchar();
}

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 179
`

9.8 POLYMORPHISM, DYNAMIC BINDING, MESSAGE PASSING


Polymorphism
The ability to take more than one form is called as polymorphism.
Dynamic Binding
Dynamic binding means the code associated with the given procedure call is not known
until the time of the call at run time.
Message Passing
Objects communicate with each another by sending and receiving information much
the same way as people pass messages to one another.
The above three OOP concept can be explained with the help of a concept in C++
called “Function Overloading”.

What is Function Overloading?


Different functions having the same name but they differ by the number of arguments
passed or by the type of arguments passed, then it is called as “Function Overloading”.
This concept of different functions having same name is not possible in C language.
Example:
#include<iostream>
using namespace std;
class Polygon
{
public:
int a, l, b, sq, rect;
float r, cir;
int area(int); // The function area is declared in three different way.
int area(int, int);
float area(float);
};
int Polygon::area(int a1)
{
a = a1;
sq = a*a; // Equation for area of square
return sq;
}
int Polygon::area(int l1, int b1)
{
l = l1;
b = b1;
rect = l * b; // Equation for area of rectangle
return rect;
}
float Polygon::area(float r1)

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 180
`

{
r = r1;
cir = 3.14*r*r; // Equation for area of circle
return cir;
}
void main()
{
Polygon obj1;
int side, length, breadth, square, rectangle;
float radius, circle;
cout<<”\n\n enter the side of a square ”;
cin>>side;
square = obj1.area(side);
cout<<”\n The area of the square is: ”<<square;
cout<<”\n\n enter the length and breadth of a rectangle ”;
cin>>length>>breadth;
rectangle = obj1.area(length, breadth);
cout<<”\nThe area of the rectangle is: ”<<rectangle;
cout<<”\n\n enter the radius of the circle ”;
cin>>radius;
circle=obj1.area(radius);
cout<<”\nThe area of the circle is: ”<<circle;
getchar();
}

Output:

We can see how “Polymorphism” is used in the above function overloading program.
In the program, we have member functions with the name “area”. This single function
name “area” is used to handle different numbers and different types of arguments.
Based upon the types of arguments passed, the area function will behave differently.
a. When only one integer is passed as an argument, this “area” member function will
find the area of a square.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 181
`

b. When 2 integers are passed as an argument, this “area” member function will find
the area of a rectangle.
c. When 1 floating point value is passed as an argument, this “area” member function
will find the area of a circle.
From the above example, we have seen that the member function “area” exists in
different forms, based on the type of the argument passed , as well as the number of
argument passed, thus emphasising the concept of “polymorphism”.

We’ll see now how “Dynamic Binding” is effected in the above function overloading
program.
Dynamic Binding is also known as “Late Binding”. The code associated with the given
procedure call is not known until the time of call at run time. It is also associated with
“Polymorphism”. A function call associated with a polymorphic reference depends on
the dynamic type of that reference.
In the above program, there are three member functions with the same name “area”.
The object “obj1” is can access all the three member functions having the same name
“area”. Only at run time, the code matching the object under the current reference will
be called. This is called as “Dynamic Binding”.
We’ll now see how “Message Passing” is effected in the above function overloading
program.
Message passing involves
Specifying the name of the object
- obj1 (in this program)
a. Name of the function (message)
- area (in this program)
b. the information to be sent (3 different
information are sent in this program)
- side
- length, breadth
- radius

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 182
`

Watch & Learn : “Function Overloading”


Click the following link or else just select the link, copy & paste the link in your browser
https://youtu.be/d7IohNyEMQ0

9.9 CONSTRUCTOR & DESTRUCTOR


Constructor:

In C++, initialisation of data members, inside the class definition


is not allowed. This is because, the data members will be
allocated with space in the memory, only at the time of
creation of objects. (Recall the topic 9.5 – Object creation & its
memory allocation). It means, we can initialise these data
members only when objects are created. C++ has a special
concept called “Constructor” which helps us to initialise the
objects ie. initialise the data members associated with the
objects.
a. A constructor is a member function whose task is to initialize the objects of its class.
b. It is a special function because its name is the same as the class name.
c. The constructor is invoked whenever an object of its associated class is created.
A constructor is declared and defined as follows:
class Integer
{
int m, n;
public:
integer(void); //constructor declared
};
integer :: integer(void) //constructor defined
{
m = n = 0;
}
Even though the constructor is a special member function, it has no return type. It just

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 183
`

bears the name of the class and will be called automatically whenever objects are
created. It must be declared only under the public access specifier.
Watch & Learn : “Constructors in C++”
Click the following link or else just select the link, copy & paste the link in your browser
https://youtu.be/a-jiPHY_gi4
There are different types of constructor. They are:
a. Default Constructor
b. Parameterized Constructor
c. Constructor with Default argument
d. Dynamic Constructor
e. Multiple Constructor
Watch & Learn : “Types of Constructors in C++”
Click the following link or else just select the link, copy & paste the link in your browser
https://youtu.be/4S7leM7G2C4

We’ll learn, the concept of constructor by learning the various types of constructors.

Default Constructor
a. A constructor that accepts no arguments is called as default constructor.
b. The default constructor for class A is A().
c. If no such constructor is defined then the compiler supplies a default constructor.
d. Therefore a statement such as A obj; invokes the default constructor of the compiler
when the object obj is created.
Example:
#include<iostream>
using namespace std;
class M2A
{
public:
int a, b;
void display()
{
cout <<”a=”<<a<<”\nb=”<<b;
}
M2A() // default constructor with no arguments
{
a = b = 0;
}
};
void main()
{

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 184
`

M2A obj; /* now constructor will be called automatically and values of a & b will
be initailised to zero */
obj.display();
getchar();
}
Output:

Parameterized Constructor
a. In practice it may be necessary to initialize data elements of different objects with
different values when they are created.
b. It is permitted in C++ by passing arguments to the constructor function when the
objects are created.
c. The constructors that take the arguments are called parameterized constructors.

M2A(int a, int b) // parameterized constructor


{
c = a;
d = b;
}
When a constructor has been parameterized the object declaration statement such as
M2A obj1; will not work
We must pass the initial values as arguments to the constructor function when an
object is declared. This can be done in two ways:
a. By calling the constructor explicitly
b. By calling the constructor implicitly
Example: M2A obj1 = M2A(0, 100); //explicit call
This statement creates the object obj1 and then passes the values 0 and 100 to it.
Example: M2A obj1(0, 100); //implicit call
This statement, sometimes called the short hand method, and is often used as it is
shorter, looks better and easy to implement.
Example:
#include<iostream>
using namespace std;
class M2A
{
public:
int a, b;
void display()
{

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 185
`

cout <<”a=”<<a<<”\nb=”<<b;
}
M2A(int c, int d) // Parameterized constructor
{
a = c;
b = d;
}
};
void main()
{
M2A obj(10, 20); /*Parameterized constructor, called automatically and values of
10 & 20 will be passed as parameters to the constructor */
obj.display();
getchar();
}
Output:

Constructor with Default argument


It is possible to define constructors with default arguments.
For example,
M2A(int a, int b=0) // b is assigned default value only if not specified
{
c = a;
d = b;
}
The default value of the argument int b is zero.
The statement
M2A obj1(5);
assigns the value 5 to data member ‘a’ and 0 to the data member ‘b’. However the
statement
M2A obj1(2, 3);
assigns a = 2 and b = 3, the actual parameter if provided will override the default value.
Example:
#include<iostream>
using namespace std;
class M2A
{
public:
int a, b;
void display()
{

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 186
`

cout <<”\na=”<<a<<”\nb=”<<b;
}
M2A(int c, int d = 0) // Parameterized constructor
{
a = c;
b = d;
}
};
void main()
{
M2A obj(10); /* Default constructor will be called automatically and 10 will be
passed to the first parameter ‘c’ & ‘d’ will have the default value */
obj.display();
M2A obj1(100, 200); /* the value 200 will override the default value of b*/
obj1.display();
getchar();
}
Output:

Dynamic Constructor
a. The constructors can also be used to allocate memory while creating objects.
b. This will enable the system to allocate the right amount of memory for each object
when the objects are not of the same size, thus resulting in the saving of memory.
Example: strings of different lengths.
c. Allocation of memory to objects at the time of their construction is known as the
dynamic construction of objects.
d. The memory is allocated with the help of “new” operator.
Example:
#include<iostream>
#include<string.h>
using namespace std;
class String
{
char * name;
int length;
public:
String()
{
length = 0;

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 187
`

name = new char[length + 1]; /* usage of new operator to allocate the


memory space during run time.*/
}
String(char *s)
{
length = strlen(s);
name = new char[length + 1];
strcpy(name, s);
}
void display()
{
cout<<name<<"\n";
}
void join(String &a, String &b);
};
void String :: join (String &a, String &b)
{
length = a.length + b.length;
delete name; //delete if it exists
name=new char[length + 1];
strcpy(name, a.name);
strcat(name, b.name);
}
void main()
{
char *first="john";
String name1(first), name2("david"), name3("louis"), s1, s2;
s1.join(name1, name2);
s2.join(s1, name3);
name1.display();
name2.display();
name3.display();
s1.display();
s2.display();
getchar();
}
Output:

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 188
`

Multiple Constructor

When more than one type of constructor is defined inside a class, then we call it as
Multiple Constructor. This is also called as “Constructor Overloading”.
Example:
// to add complex numbers
//you can write even simpler programs.
/* the main objective of the following program is to learn complex number adding as
well as to learn object handling methods*/

#include<iostream>
class complex
{
float x, y;
public:
complex() //constructor with no argument
{
}
complex(float a) // constructor with one argument
{
x=y=a;
}
complex(float real, float img) // constructor with two arguments
{
x = real;
y = img;
}
complex sum( complex, complex);
void show(complex);
};
complex complex :: sum(complex c1, complex c2)
{
complex c3;
c3.x = c1.x + c2.x;
c3.y = c1.y + c2.y;
return c3;
}
void complex::show(complex c)
{
cout<<c.x<<" + i"<<c.y;
}
void main()
{

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 189
`

complex A(2.0, 3.0);


complex B(1.6);
complex C, D;
C = D.sum(A, B);
D.show(C);
getchar();
}
Output:

Destructor:
A destructor, as the name implies, is used to destroy the objects that have been created
by a constructor. Like a constructor, the destructor is a member function whose name
is the same as the class name, but is preceded by a tilde ~ symbol. For example, the
destructor for the class M2A is defined as follows:
~M2A()
{
}

a. A destructor never takes any argument nor does it return any value.
b. It will be invoked implicitly by the compiler upon the exit from the program or block
or function, to clean up the storage that is no longer accessible.
c. It is always recommended to use destructors in a program, which releases the
memory space for future use.
Example:
#include<iostream>
using namespace std;
int count=0; // Global Declaration
class M2A
{
public:
M2A()
{
count++;
cout<<"\n Object No "<<count<<" created";
}
~M2A()
{
cout<<"\n Object No: "<<count<<" destroyed";
count--;

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 190
`

getchar();
}
};
void main()
{
cout<<"\n We have entered main function\n";
M2A obj1, obj2, obj3, obj4;
{
cout<<"\n We have entered the first block\n";
M2A obj5;
}
{
cout<<"\nWe have entered the second block\n";
M2A obj6;
}
cout<<"\n Re-entered the main function\n";
getchar();
}
Output:

Watch & Learn : “Destructor in C++”


Click the following link or else just select the link, copy & paste the link in your browser
https://youtu.be/hI-XxfpzVBM

9.10 Operator Overloading & Inheritance


Operator Overloading
 C++ tries to make the user defined data types in the same way as the built in types.
 C++ permits us to add two variables of user defined types with the same syntax that
is applied to the basic types.
 This means C++ provides the operators a special meaning.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 191
`

 The mechanism of giving such special meanings to an operator is known as operator


overloading.
We can overload all the C++ operators except the following
 Class member access operators
Membership operator - .
Pointer to member operator - .*
 Size of operator – sizeof
 Scope Resolution operator - ::
 Conditional operator - ?:
To define an additional task to an operator, we must specify what it means in relation
to the class to which the operator is applied. This is done with the help of a special
function called operator function.
The general form of an operator function is:
return type classname :: operator op(arglist)
{
function body;
}

Watch & Learn : “Operator Overloading”


Click the following link or else just select the link, copy & paste the link in your browser
https://youtu.be/_2fTcwdemSo
Operators are two types:
1) Unary Operators.
eg) unary +,unary -,++,--
2) Binary Operators
eg) addition operator +, Subtraction operator -, Multiplication operator
*,Division operator /,Comparison operator ==
Operator overloading can be done following 2 concepts:
1) Member function concept
2) Friend function concept (This we are not going to discuss)
Using ordinary member function concept, we can overload the unary & binary
operators by following the hints shown below:
NUMBER OF ARGUMENTS TO BE PASSED IN THE OPERATOR FUNTION

TYPES OF OPERATOR ORDINARY MEMBER FUNCTION


CONCEPT

UNARY OPERATORS NO ARGUMENTS

BINARY OPERATORS ONLY ONE ARGUMENT

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 192
`

Example for Overloading Unary Operator (Unary minus)


• Unary minus
– Takes no arguments for member functions.
#include<iostream>
using namespace std;
class space
{
public:
int x,y,z;

void getdata(int a,int b,int c);


void display();
void operator-() ; //overload unary minus
};
void space :: getdata( int a,int b,int c)
{
x=a;
y=b;
z=c;
}
void space ::display()
{
cout<< x <<"\t"<< y <<"\t"<< z << endl;
}
void space::operator -() //
{
x=-x;
y=-y;
z=-z;
}
void main()
{
space S;
S.getdata(10,-20,30);
S.display();
-S; //activates the operator -() function
S.display();
getchar();
}

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 193
`

Output:

Watch & Learn : “Unary Operator Overloading”


Click the following link or else just select the link, copy & paste the link in your browser
https://youtu.be/jcn70G4YhPw

Example for Overloading Binary Operator


(Binary minus (Subtraction operator -))
• Binary minus
Takes one argument for member functions.
#include<iostream>
using namespace std;
class subtract
{
public:
int x;

void getdata(int a);


void display();
subtract operator-(subtract ) ; //overload unary minus
};
void subtract :: getdata( int a)
{
x=a;
}
void subtract ::display()
{
cout<< "\nThe subtracted value is:"<<x<<"\n";
}
subtract subtract::operator -(subtract S)
{
subtract temp;
temp.x=x-S.x;
return temp;
}
void main()
{
subtract S1,S2,S3;

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 194
`

S1.getdata(20);
S2.getdata(10);
S3=S1-S2; //activates the operator -() function. The object S2 will be passed as an
argument. This is equivalent to S3=S1.operator+(S2);
S3.display();
getchar();
}
Output:

Note: As a rule in overloading the binary operators, the left hand operand is used to
invoke the operator function and the right hand operand is passed as an argument.

This can be understood by the following illustration:

Watch & Learn : “Binary Operator Overloading”


Click the following link or else just select the link, copy & paste the link in your browser
https://youtu.be/7QVvV-dkyvE

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 195
`

Inheritance
Have you ever noticed? Your grandma saying, “You
behave as if my son does”. Of course, you are unique
and you have your own characters & behaviours. But
even then, you would have inherited some of the
characters of your father in your gene. Inheriting the
properties from the “Parent” apart from the one
that exists within you is simply called as
“Inheritance”

 C++ strongly supports the concept of reusability.


 The C++ classes can be reused in several ways
 Once a class has been written and tested, it can be adapted by other programmers
to suit their requirements.
 This is basically done by creating new classes, reusing the properties of the existing
ones.
 The mechanism of deriving a new class from an old one is called inheritance (or
derivation)
 The old class is referred to as the base class or the super class and the new class is
called the derived class or the sub class

Defining derived classes


A derived class can be defined by specifying its relationship with the base class
in addition to its own details.

The general form of defining a derived class is:


class derived-class name : visibility-mode base-class-name
{
………….// members of derived class
};

1. The colon indicates that derived-class-name is derived from the base-class-name.


2. The visibility-mode is optional and if present, may be either private or public.
3. The default visibility-mode is private.
4. Visibility-mode specifies whether the features of the base class are privately derived
or publicly derived.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 196
`

Example:

 When a base class is privately inherited by a derived class, public members of the
base class become private members of the derived class and therefore the public
members of the base class can only be accessed by the member functions of the derived
class.
 On the other hand, when the base class is publicly inherited, public members of a
base become public members of the derived class and therefore they are accessible to
the objects of the derived class.

Watch & Learn : “Inheritance in C++”


Click the following link or else just select the link, copy & paste the link in your browser
https://www.youtube.com/watch?v=5pJyKzON8Ww&list=PLrKBFf87Cy9BVBAZ1
Y-6Olzz0KTU4Qw6L&index=39

Visibility of the inherited members:

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 197
`

Watch & Learn : “Access Specifiers in Inheritance”


Click the following link or else just select the link, copy & paste the link in your browser
https://www.youtube.com/watch?v=F75zgvDKWI8&list=PLrKBFf87Cy9BVBAZ1Y-
6Olzz0KTU4Qw6L&index=41

Types of Inheritance:
Single Inheritance

When one base class is inherited by only one derived class, it is called as
Single Inheritance.

Watch & Learn : “Single Inheritance”


Click the following link or else just select the link, copy & paste the link in your browser
https://www.youtube.com/watch?v=VmDUgxflYSQ&list=PLrKBFf87Cy9BVBAZ1Y
-6Olzz0KTU4Qw6L&index=40

Multiple Inheritance

A class inherits its properties from more


than one class ie one derived class
inheriting its properties from more than
one base class is called Multiple
Inheritance

Watch & Learn : “Multiple Inheritance”


Click the following link or else just select the link, copy & paste the link in your browser
https://youtu.be/2DKRmhBmH7E

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 198
`

Hierarchical Inheritance

One base class is


inherited by more than
one derived classes is
called Hierarchical
Inheritance

Watch & Learn : “Hierarchical Inheritance”


Click the following link or else just select the link, copy & paste the link in your browser
https://youtu.be/9ZpeeilvNQY

Multilevel Inheritance
One class say A serves as the base class for the derived class
B, which in turn acts as base class for another class C. The
class B acts as an intermediate class since it provides a link
for the inheritance between A and C. The chain ABC is called
the inheritance path
Such levels of inheritance is called multilevel inheritance
and these process can be extended to any number of levels.

Watch & Learn : “Multi Level Inheritance”


Click the following link or else just select the link, copy & paste the link in your browser
https://youtu.be/t9I4Xmxa-3Q

Hybrid Inheritance
There could be situations
where we need to apply two
or more types of
inheritance to design a
program which results in a
new type of inheritance
called Hybrid Inheritance.
let us now take an example
that takes the combination
of multilevel and multiple
inheritance

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 199
`

Watch & Learn : “Hybrid Inheritance”


Click the following link or else just select the link, copy & paste the link in your browser
https://youtu.be/1VdYat6Yqxs

Program Example: - Single Inheritance


#include<iostream>
using namespace std;
class Base
{
public:
int a;
void getdata()
{
cout<<"enter the value of a";
cin>>a;
}

};
class Derived:public Base //class 'Base' is derived by the class 'Derived'. The properties
of 'Base' clase is derived in 'public' visibility mode.
{
public:
int b,c;
void get()
{
getdata(); // accessing the member function of Base class
cout<<"enter the value of b";
cin>>b;
}
void sum()
{
c=a+b; // data member of Base class is used inside the Derived class
cout<<"The sum is:"<<c<<endl;
}
};
void main()
{
Derived obj; // object is created for the Derived class
obj.get();
obj.sum();
getchar();
getchar();

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 200
`

}
Output:

(Try out the programs on your own for other types of inheritance)

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 201
`

Time to recall & Test yourself!

1. What is meant by dynamic binding? How is it useful in OOP?


2. Every operator has a name. What is the operator :: called in C++?
3. The new operator is used to allocate memory dynamically. Which operator is used
to deallocate the memory space?
4. If the value of a is assigned as a = 10, then the statement cout<<a++, will print
_________
5. The operator << which we represent along with the cout statement is called as
_________ operator
6. The operator >> which we represent along with the cin statement is called as
_________ operator
7. The << operator is called as insertion operator, which is also called as ________
a) put to operator b) get from operator
8. The >> oprator is called as extraction operator, which is also called as ________
a) put to operator b) get from operator
9. The members of the structure in ‘C’ are public by default. What about the members
of the class in C++?
10.Can you initialize the data members of a Class, inside the class definition itself? Can
you find the different ways to initialize the data members of the class?
11.For the class “NTTF”, with data members M1_A, M2_A & M3_A and member
functions mark_display() & Rank_order(), the objects ob1 & ob2 are created. How
these objects are memory mapped to the data members & member functions of the
class NTTF, Can you draw a rough sketch of Object memory allocation?
12.Constructors are used to initialize the objects, wheras, ___________ are used to
destroy the objects.
13.Suppose a class has a default constructor, a parameterized constructor and a default
argument constructor defined in it, then we call the constructors are __________ in
the class.
a) Overloaded b)overridden c)hidden
14.The class is defined with data members and member functions. Such wrapping up
of members of the class as a single unit is called as _____________.
15.A class has many member functions but all the member functions bear the same
name. Is it possible to create a class in such manner in C++?
16.The name of the class is “NTTF”. For the class “NTTF” we have created the objects
Ob1 & Ob2. What is the data type of the objects Ob1 & Ob2?
17.List the 3 access specifiers.

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 202
`

18.In a C++ program, m1 is a public member of the class “NTTF”. Can we use the
statement NTTF::m1=10 inside any of the member functions of the class NTTF?
(Write a program and tell the answer)

19.NTTF is the classname. The private members of the class are m1 & m2. The public
members of the class are m3 & m4. obj1 is the object of the class type “NTTF”. Which
of the following statements will raise error?Why?
a) obj1.m3=100; b) obj1.m1=100; c) obj1.m2=100; d) obj1.m4=100;

20.When a member function is called from another member function of a class, we call
that the member functions are _____________
a) public b) nested c) destroyed d) hidden

21.Instead of creating individual objects as ob1, ob2 & ob3, we can create objects as
________, by implementing the “Array of objects”.

22.Can objects be passed as parameter to member functions? Give an example


program.

23.There are many more concepts in C++ which are still untouched in your syllabus.
Surf the net and explore more on :
a. Operator Overloading b. Inheritance and Types c. Friend functions d. Virtual
Base Class e. Abstract Class

24. Which of the following explains Polymorphism?


a. int func(int, int); b. int func(int);
float func1(float, float); int func(int);
c. int func(float); d. int func();
float func(int, int, char); int new_func();

25. Which of the following feature of OOPs is not used in the following C++ code?

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 203
`

class A
{
int i;
public:
void print(){cout<<"hello"<<i;}
}
class B
{
int j;
public:
void assign(int a){j = a;}
}
a. Abstraction b. Encapsulation c. Polymorphism

26. Which operator is overloaded for a cout object?


a. >> b. << c. < d. >

27. What will be the output of the following C++ code?


#include <iostream>
using namespace std;
class A{
public:
A(){
cout<<"Constructor called\n";
}
~A(){
cout<<"Destructor called\n";
}
};
int main(int argc, char const *argv[])
{
A *a = new A[5];
return 0;
}
a. “Constructor called” five times b. “Constructor called” once
c. Error d. Segmentation fault

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 204
`

28. What will be the output of the following C++ code?


#include <iostream>
using namespace std;
class A
{
int a;
public:
A() { a = 5;}
};
int main()
{
A obj;
cout << obj.a;
}
a. 5 b. Garbage value c. Compile-time error d. Run-time error

29. Which of the following is the correct difference between cin and scanf()?
a. both are the same b. cin is a stream object whereas scanf() is a function
c. scanf() is a stream object whereas cin is a function
d. cin is used for printing whereas scanf() is used for reading input

30. What is dynamic binding?


a. The process of linking the actual code with a procedural call during run-time
b. The process of linking the actual code with a procedural call during compile-
time
c. The process of linking the actual code with a procedural call at any-time

NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 205

You might also like