Computer Programming
Computer Programming
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
NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 1
`
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.
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
`
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
`
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.
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.
NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 6
`
NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 7
`
Time to recall
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”.
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
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.
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.
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.
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
`
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.
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
`
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
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
`
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
`
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
`
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
`
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
`
Unary Operators: These operators require only single operand to act upon.
Example increment and decrement operators.
NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 18
`
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
`
NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 20
`
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;
NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 21
`
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.
NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 22
`
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
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
`
NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 25
`
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
`
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.
NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 27
`
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
`
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.
NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 31
`
Time to recall
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
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
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
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.
NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 36
`
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
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
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)
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)
NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 40
`
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)
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
NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 42
`
10
5
25
Special Operators
NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 43
`
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
`
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: (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
`
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.
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.
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
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.
___________________________________________________________________
NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 49
`
NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 50
`
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
`
NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 52
`
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.
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
`
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:
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
`
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
`
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
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
There are many library functions under this category. We are going to learn few of
them.
NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 59
`
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
`
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:
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
`
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
`
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
`
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
NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 66
`
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
`
NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 68
`
NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 69
`
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
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
`
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
NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 71
`
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)
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:
NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 76
`
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);
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’.
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.
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!
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.
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.
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
`
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.
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.
Continuous Arrangement
NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 86
`
Contiguous Arrangement
Now we’ll have a look on contiguous arrangement.
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.
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
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.
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).
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
NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 90
`
#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:
NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 91
`
dimensional arrays.
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
NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 93
`
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.
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
Here, [^\n] indicates that scanf() will keep receiving the characters into name until \n
is encountered.
NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 95
`
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.
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
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
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:
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.
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.,
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
`
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.
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.
Function Definition:
The piece of code within a block, which defines a specific task is called as the definition
of the function.
NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 101
`
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
`
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
`
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
`
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”.
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
`
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.
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)
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
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
`
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
//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
`
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.
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.
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
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
`
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
`
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
`
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.
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
`
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]
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
`
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
`
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.
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:
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:
"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.
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( ) 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.
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
`
#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:
Preprocessor Syntax/Description
Syntax: #define
Macro This macro defines constant value and can be any of the basic
data types.
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 : ?
OUTPUT:
RAJU is defined. So, this line will be added in this C file
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
NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 141
`
#endif
return 0;
}
OUTPUT:
#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
#include <stdio.h>
void function1( );
void 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
`
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 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);
}
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);
}
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
`
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.
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.
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
`
NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 153
`
Output:
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.)
NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 154
`
OUTPUT:
NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 155
`
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:
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
`
This copying of all structure elements at one go has been possible only because the
structure elements are stored in contiguous memory locations.
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
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:
NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 162
`
NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 163
`
int no;
char name[20];
}
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.
NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 165
`
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
`
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
`
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
`
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();
}
Output:
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
`
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.
NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 173
`
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
`
NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 176
`
Output:
NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 177
`
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
`
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
`
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.
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:
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
`
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
`
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:
NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 191
`
NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 192
`
NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 193
`
Output:
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.
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”
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.
NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 197
`
Types of Inheritance:
Single Inheritance
When one base class is inherited by only one derived class, it is called as
Single Inheritance.
Multiple Inheritance
NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 198
`
Hierarchical Inheritance
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.
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
`
};
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
`
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”.
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
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
NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 204
`
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
NTTF_DIPLOMA IN MECHATRONICS ENGINEERING & SMART FACTORY (CP15)_SEMESTER 3_COMPUTER PROGRAMMING_MASTER FILE 205