C and C++ Notes by Ram
C and C++ Notes by Ram
First Generation Languages: These are low-level languages like machine language.
Second Generation Languages: These are low-level assembly languages used in kernels and
hardware drives.
Third Generation Languages: These are high-level languages like C, C++, Java, Visual Basic and
JavaScript.
Fourth Generation Languages: These are languages that consist of statements that are similar to
statements in the human language. These are used mainly in database programming and scripting.
[email protected]
Examples of these languages include Perl, Python, Ruby, SQL, MatLab (MatrixLaboratory).
Fifth Generation Languages: These are the programming languages that have visual tools to develop
a program. Fifth generation languages include Mercury, OPS5, and Prolog.
The first two generations are called low level languages. The next three generations are called high
level languages.
Programming Languages
1. Before a program can be executed, it must be translated from the programming language (source
code) to the machine instructions of the hardware that is to execute it, and the executable program
must be loaded into main memory.
2. The first phase of the process is translation from source code to machine code. This is done by a
compiler or assembler.
3. The C preprocessor handles the directives that begin with "#", such as #include, #define.
4. In order to make a complete program, various separately compiled modules must be combined.
This is done by the linker. Finally, the linked program is loaded into memory by the loader.
1
Q: What is an Algorithm? Explain?
A: Algorithm: It is a step by step procedure to solve a problem. In normal language, algorithm is
defined as a sequence of statements which are used to perform a task.
[email protected]
Performance analysis of an algorithm is performed by using the following measures…
1. Space required to complete the task of that algorithm (Space Complexity). It includes program
space and data space
2. Time required to complete the task of that algorithm (Time Complexity)
Common shapes: The following are some of the commonly used shapes used in flowcharts.
2
Ex: Following flow chart describes steps for comparing two numbers
start
Read A, B
True
[email protected]
Prints “Equal” stop
INTRODUCTION TO C:
3
‘C’ is a programming language developed by Dennis Ritchie in 1972 at AT & T’s Bell
Laboratories of USA. Dennis Ritchie received the features of B and BCPL programming languages
added some of his own and developed ‘C’ programming language. Dennis Ritchie main achievement
is the restoration of the lost generality in BCPL and B and still keeping it powerful.
Today ‘C’ language is running under a number of operating systems including MS-DOS for
Micro computers.
HISTORICAL DEVELOPMENT OF C :
[email protected]
Committee
1967 BCPL (Basic Combined Martin Richards at Could deal with only
Programming language) Cambridge specific problems
University
1). General purpose programming language: C-Programming language is used to implement any
[email protected]
kind of applications such as Mathematical oriented, Research oriented, Graphics oriented, Scientific
oriented and Business oriented applications. That’s why C is called as General purpose programming
language.
2). Powerful programming language: C is very efficient, popular and powerful programming
language. It is designed to perform system software and as well as data structures.
3). Middle level language: Every programming language can be classified into two categories. They
are High level language and Low level language.
a). High level language: It is designed to perform for a faster program development. It is also called
as Problem oriented language.
b). Low level language: It is designed to perform for a faster program execution that is better machine
efficiency. It is also called as Machine oriented language.
Our C language stands in between these two categories i.e., C-language contains the features of
both High level and Low level languages. That is why C-language is a Middle level language.
4). Portability: C program is suitable with majority of operating systems. Hence it is portable to other
systems even if the operating system differs.
5). Modularity: Modularity is one of the important advantages of C-language. We can split the
program into number of modules instead of writing it sequentially and repeated number of times.
Modularity allows reusability of the modules
It avoids the repetition of calculations
It improves understandability
It reduces the length of a program
It reduces the work burden
1. Alphabets or Letters:
A, B, C, ………, Z
a, b, c, ……….., z
2. Digits:
0, 1, 2, 3, ………, 9
[email protected]
3. Blank spaces or White spaces:
Blank space, Tab space and New line
4. Special symbols:
, Comma / Slash
. Period ~ Tilde
; Semicolon _ Underscore
: Colon > Closing angle bracket or Greater than
? Question mark < Opening angle bracket or Less than
‘ Apostrophe ( Left parenthesis
“ Double quotes ) Right parenthesis
! Exclamation mark [ Left bracket
| Vertical bar ] Right bracket
{ Left brace (opening brace) $ Dollar sign
} Right brace (closing brace) % Percent sign
# Number sign & Ampersand
^ Carret * Asterisk
+ Plus sign - Minus sign
[email protected]
i. Octal integers
ii. Decimal integers
iii. Hexa-decimal integers
b. Real constants: Real constants are often called Floating point constants. The Real constants are in
two forms. They are Fractional form and Exponential form.
2. Non-numeric constants: Non-numeric constants are also called as Character constants. These are
divided into two parts. They are,
a. Single character constants
b. String character constants
a. Single character constant: It is either a single alphabet or a single special symbol or a single blank
space enclosed with in a pair of a single quotation marks (‘ ’). The maximum length of the single
character constant is 1 character.
Ex: ‘a’, ‘A’, ‘&’, ‘+’
7
Keywords are also called as “Reserved words”. There are 32 keywords available in C-
language. All keywords must be written in lower case, because C-programming language is a case-
sensitive programming language.
[email protected]
do goto signed while
Types of variables:
1. A constant stored in a memory location with an Integer variable name that must be an integer
constant.
2. A constant stored in a memory location with a Real variable name that must be a real constant.
3. A constant stored in a memory location with a Character variable name that must be a character
constant.
Rules for constructing variable names:
1. A variable name is any combination of alphabets, digits or under score character.
2. It must be begin with an alphabet.
3. Maximum length of the variable names is 1 to 8 characters.
4. Variable name should not be a keyword.
5. Capital letters are not allowed.
6. Blank spaces are not allowed.
7. Special symbols are not allowed except under score character (_). Under score character is
allowed between any two characters.
Ex: a, s1, sum, s_i
8
Q: What are the types of Instructions available in C-Language?
Ans: C-Instructions: The different types of constants, variables and keywords are combined to form
instructions. Basically 4 types of instructions are available in C-programming language. They are,
1. Type declaration instructions.
2. Input / Output instructions.
3. Arithmetic instructions.
4. Control instructions.
1. Type declaration instructions: These instructions are used to declare the data type of variables
used in a program.
2. Input / Output instructions: These instructions are used to perform the function of supplying
[email protected]
input data to a program and getting the output results from it.
3. Arithmetic instructions: These instructions are used to perform arithmetic operations between
constants and variables.
4. Control instructions: These instructions are used to control the sequential flow of execution of
various statements in a C-program.
9
Memory Conversion
Data type Data Range
size character
%c (single)
char 1 Byte 0 to 255 (or) - 128 to + 127
%s (string)
[email protected]
task.
To write a C-program, we first create functions and then put them together. C-program may
contain one or more sections. That is,
Documentation Section
Link Section
Definition Section
Global Declaration Section
main( )
{
Declaration Part
Executable Part
}
Sub-program Section
Function-1
Function-2
. User-defined
. Functions
Function-n
Documentations Section: It contains the comment lines that are like program names, author names, date,
time and any understandable messages.
Ex: /* message */
Link Section: This section is used to provide instructions to the C-compiler to link the functions to the C-
system library.
Ex: #include<math.h>
#include<string.h>
10
Definition Section: This section is used to define all the symbolic constants.
Ex: #define PI 3.14
Global Declaration Section: In this section, there are some variables that are used in more than one
function such type of variables are called as “Global variables”. These variables must be declared in
the Global declaration section.
main( ) function section: Every C-program must have one main( ) function section. This section
contains two parts. They are,
a) Declaration part
b) Executable part
a) Declaration part: It declares all the variables used in the executable part. There is at least one
[email protected]
statement in the executable part. These two parts must be appeared between the opening and closing
braces.
b) Executable part: The program execution begins at the opening brace { and ends at the closing
brace }. The closing brace of the main( ) function section is a logical end of the program.
All the statements in the declaration and executable parts must be end with semicolon (;).
Sub-program Section: This 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
section although they may appear in any order.
In a structure of C-program, all the sections are optional except main( ) function section.
1. Keywords: Keywords are the words whose meaning has already been explained to the
compiler. So that every Keyword has a fixed meaning and that meaning cannot be changed.
11
Keywords cannot be used as variable names. If we do like that then we are giving a new
meaning to the keywords which is not allowed by the compiler. Keyword serves as basic
building blocks for program statements.
Keywords are also called as “Reserved words”. There are 32 keywords available in C-
language. All keywords must be written in lower case, because C-programming language is a
case-sensitive programming language.
2. Identifiers: Identifiers are user-defined tokens. They are used for naming variables, arrays,
functions, labels and etc. Each language has its own rules for naming these Identifiers.
Rules for Identifiers:
a. They can have alphabets, digits and underscore are permitted.
b. The name should start with an alphabet.
[email protected]
c. Uppercase and lowercase letters are different.
d. Keyword is not allowed as an identifier.
e. They can have number of characters.
3. Constants: Constants refer to fixed values that do not change during the program execution.
C supports several kinds of literal constants. They include integers, characters, floating point
numbers and strings. Literal constants do not have memory locations. For example:
4. Operators: An operator is a special symbol that takes one or more arguments and operates on
them to produce a result.
In C, there are different types of operators are used to perform different types of
operations. They are,
i. Arithmetic operators
ii. Relational operators
iii. Logical operators
iv. Assignment operator
v. Increment and Decrement operators
vi. Conditional operator
12
vii. Bitwise operators
viii. Special operators
5. Separators: Separators are symbols used to indicate where groups of code are divided and
arranged.
In C, there are different types of separators. They are,
[email protected]
class using object
1. Arithmetic operators: C-programming language provides all the basic arithmetic operators.
They are,
Operator Meaning
+ Addition or Unary Plus
13
All these operators can be used in integer type data. “ +, -, *, / ” can be used in real type data.
But “%” operator can not be used in real type data. Integer division cut offs any fractional part. The
modulo division produces the “reminder” of an integer division.
Ex: a+b, a-b, a*b, a/b, a%b
Here a, b are variables and also known as operands. Arithmetic operators are used to solve
different operations. Such as,
a. Integer arithmetic operation
b. Real arithmetic operation
c. Mixed-mode arithmetic operation
a. Integer arithmetic operation: When both the operands in a single arithmetic expression, such as
a+b are integers the expression is called as integer expression and that operation is called as
[email protected]
“Integer arithmetic operation”.
Integer arithmetic always gives an integer value.
Ex: If a, b are integers with a=14, b=4 then
a+b = 18
a-b = 10
a*b = 56
a/b = 3
a%b = 2
b. Real arithmetic operation: In arithmetic expression all operands constants are of real type that
expression is called as real type expression and that operation is called as “Real arithmetic operation”.
Real arithmetic always gives real value. The operator “%” can not be used with real operands.
Ex: If a=5.0, b=2.0 then
a+b = 7.0
a-b = 3.0
a*b = 10.0
a/b = 2.5
c. Mixed-mode arithmetic operation: When one of the operands is real type and another one is
integer type then that expression is called as Mixed-mode expression and that operation is called as
Mixed-mode arithmetic operation.
In this situation, only the real operation is performed and the result is always a real type value.
Ex: If a=5.0, b=2 then
a+b = 7.0
a-b = 3.0
a*b = 10.0
a/b = 2.5
14
2. Relational operators: The operators which are used to make comparisons between the two
expressions called as “Relational operators”. These are used to take certain decisions.
An expression such as a < b or n = = 0 containing a relational operator termed as a relational
expression. The value of a relational expression is either ‘1’ or ‘0’. ‘1’ means True and ‘0’ means
False. C-language supports six relational operators. They are,
[email protected]
!= Not equal to 3!= 4 True
3. Logical operators: Logical operators are used between two or more relational conditions.
These operators return either ‘1’ or ‘0’. ‘1’ means true and ‘0’ means false. C supports three
logical operators.
15
6. Conditional operator: The conditional operator is an equivalent form of “if – else” condition.
This operator is a combination of “ ? : ”. It is also called as “Ternary operator”, because it is used on
three operands.
Syntax: Condition ? ture-statement : false-statement;
7. Bitwise operators: Bitwise operators are used for maintaining the data at bit level to perform
bitwise operations. These operators are used for “Testing the bits” or “Shifting the bits either Left or
Right”.
[email protected]
The Bitwise operators in C-language are,
Operator Meaning
& Bitwise AND
| Bitwise AND
^ Bitwise Exclusive OR (XOR)
<< Left shift
>> Right shift
~ Once complement
Bitwise AND (&): The result of “AND” operation is ‘1’ if both are true, otherwise ‘0’.
Ex: a = 1 1 0 0
b = 1 0 1 0
a&b = 1 0 0 0
Bitwise OR ( | ): If at least one of the bits has a value ‘1’ then the result of “OR” operation is ‘1’
otherwise ‘0’.
Ex: a = 1 1 0 0
b = 1 0 1 0
a|b = 1 1 1 0
Bitwise Exclusive OR (XOR (^)): If only one of the bits is ‘1’ then the result of “XOR” operation is
‘1’ otherwise ‘0’.
Ex: a = 1 1 0 0
16
b = 1 0 1 0
a^b = 0 1 1 0
Bitwise Left shift (<<): The result of Left shift “<<” operation is shifts ‘n’ bits left.
Ex: a = 1 0 1 1 1 1 0 1
a<<3 = 1 1 1 0 1 0 0 0
Bitwise Right shift (>>): The result of Right shift “>>” operation is shifts ‘n’ bits right.
Ex: a = 1 0 1 1 1 1 0 1
a>>2 = 0 0 1 0 1 1 1 1
Bitwise Once complement (~): If the bit value is ‘1’ then the result of the complement operator is ‘0’.
i.e., reverse of the given bit value.
[email protected]
Ex: a = 1 1 0 1
~a = 0 0 1 0
Truth Table:
a b a&b a|b a^b ~a
1 1 1 1 0 0
1 0 0 1 1 0
0 1 0 1 1 1
0 0 0 0 0 1
8. Special operators: C supports some special operators such as comma (,) operator, sizeof
operator, pointer operators ( & and * ) and member selection operators (. and ->).
The basic evaluation procedure includes two left-to-right passes through the expression.
During the first pass, the high level priority operators (if any) are applied first. During the second
pass, the low level priority operators (if any) are applied next.
Ex: x = a-b/3+c*2-1;
17
When a=9, b=12 and c=3, the statement becomes
x = 9-12/3+3*2-1;
First pass:
Step 1: x = 9-4+3*2-1; (12/3 evaluated)
Step 2: x = 9-4+6-1; (3*2 evaluated)
Second pass:
Step 3: x = 5+6-1; (9-4 evaluated)
Step 4: x = 11-1; (5+6 evaluated)
Step 5: x = 10; (11-1 evaluated)
[email protected]
two or more parenthesis appears, then the expression is evaluated from left to right.
Take the same expression with parenthesis as,
9 -12 / (3+3)*(2-1)
First pass:
Step 1: 9 -12 / 6 * (2-1)
Step 2: 9 -12 / 6 * 1
Second pass:
Step 3: 9-2*1
Step 4: 9–2
Third pass:
Step 5: 7
Q: What is casting? What are the rules that are used in automatic casting?
A: Casting: The process of converting one data type to another is called “casting”.
We may have the situations, where there is a need to store a value of one data type into a variable
of another data type. In such situations, we must cast the value.
The syntax is, data type variable1 = type (variable2);
It is possible to assign a value of one type to a variable of different type without any casting. C++
does the conversion of the assigned value automatically. This is known as “Automatic type
conversion”. It is also called as “Implicit casting”.
Automatic type conversion is possible only if the destination type has enough precession to store
the source value.
For example, if one of the operand is an int and the other is a float, the int is converted into a
float is wider than an int.
The process of assigning a larger type to a smaller one is known as Narrowing conversion. It is
also called as “Explicit type casting”. Note that narrowing may result in loss of information.
[email protected]
Casting into a smaller type may result in a loss of data. That is, casting a floating point value
to an integer will result in a loss of the decimal part.
Q: Write about Back slash character constants in C? (or) Write about Escape sequences in C?
Ans: Back slash character constants (Escape sequences): C supports some special back slash
character constants. These are used in output functions. For example, the symbol “\n” is represented
for “new line” character.
Note that each one of them represents one character, although they consist of two characters.
These characters combinations are known as “Escape sequences”.
Character Purpose
\n new line
\t tab space
\b back space
\’ single quote
\” double quotes
\\ back slash
[email protected]
In our C-language, the various formatted input and output statements are,
a) scanf( ): It reads the formatted text from the keyboard. It is an input statement.
c) fscanf( ): It can be used in file operations. It is used to read the formatted text.
d) fprintf( ): It can be used in file operations. It is used to write the formatted text.
e) fgetc( ): It can be used in file operations. It is used to get the character from a file.
f) fputc( ): It can be used in file operations. It is used to put the character to a file.
g) fgets( ): It can be used in file operations. It is used to get the string from a file.
h) fputs( ): It can be used in file operations. It is used to put the string to a file.
Unit-2
20
Q: Explain the Control statements in C programming language?
Ans: Control statements:
C-program is a set of statements. If no conditions and no repetitions of calculations are
necessary then C-program can be executed in a sequential order.
If we need to change the sequential flow of execution then the control statements are used to
control the flow of execution of statements based on certain conditions. Control statements are also
called as “Control structures”.
Controls statements can be divided into some different groups. They are,
1. Conditional control statements
2. Multi-way conditional control statement
3. Jumping control statements
[email protected]
4. Loop control statements
1. Conditional control statements: The conditional control statements can be implemented by using
the keyword “if” in C-language.
if statement: The “if statement” is a powerful decision making control statement and it is used to
control the flow of execution of statements. It is basically a two way decision statement. It takes the
following general form.
Syntax: if (test-condition)
{
Statement block;
}
It allows the compiler to check the test condition first and then depending on whether the result
of condition is true or false, it transfers the control to a particular statement.
Start
True
Test
Conditio
n
False
Two-way branching
The if statement may be implemented in different forms depending on the complexity of the
conditions to be tested. They are,
a. simple if
21
b. if - - - else
c. nested if
d. if - - - else if
a. simple if: The if statement is used to control the flow of execution of the statements. The syntax
of simple if statement is,
Syntax: if (test-condition)
{
Statement block;
}
statement-x;
[email protected]
False
Conditio
n?
True
Statement Block Statement-x
The test condition must be represented within the parenthesis ( ). The expression becomes true
or false. If test condition is true then the statement block will be executed. If the test condition is false
then the statement block will be skipped and the execution will jump to statement-x. The statement
block will be a single statement or set of statements.
b. if else: The if else statement is an extension of the simple if statement. The syntax of if else
statement is,
Syntax: if (test-condition)
{
True-statement block;
}
else
{
False-statement block;
}
statement-x;
False
Conditio False Statement Block
n?
True
True Statement Block Statement-x
22
In the above, if the test condition is true then the true block statement(s) are executed,
otherwise the false block statement(s) are executed. Either true or false block will be executed, but
both blocks will not be executed. After the executing any statement block then the control is
transferred to the statement-x.
c. Nested if: When a series of conditions are involved, we can use more than one if—else statement
in nested form. That is, if statement combining another if statement is called as the “nested if
statement”. The syntax of “nested if” is,
Syntax: if (condition-1)
{
if (condition-2)
{
Statement block-1;
}
[email protected]
else
{
Statement block-2;
}
}
else
{
if (condition-3)
{
Statement block-3;
}
else
{
Statement block-4;
}
}
statement-x;
Flow chart:
Start
True False
Statement-x
23
In the above, if the test condition-1 is true, again it checks the condition-2. If the test condition-
2 is also true then the statement block-1 will be executed. If the test condition-2 is false then statement
block-2 will be executed. If the test condition-1 is false, then it checks the test condition-3. If it is true
then the statement block-3 will be executed, otherwise statement block-4 will be executed. After
execution of any statement block, finally the control is transferred to the statement-x.
d. if - - - else if: This is another way of putting ifs together when multi path conditions are involved.
A multi path condition is a chain of ifs in which the statement associated with each ‘else’ and ‘if’.
Syntax: if (condition-1)
{
Statement block-1;
}
else if (condition-2)
{
[email protected]
Statement block-2;
}
-----
-----
else if (condition-n)
{
Statement block-n;
}
else
{
Default statement block;
}
Statement-x;
Flow chart:
Start
True
Cond- Statement Block-1
1?
False
True
Cond- Statement Block-2
2?
False
True
Cond- Statement Block-n
n?
False
24
The above construction is known as “else if” ladder. The conditions are tested from top of the
ladder. As soon as a true condition is found the statement block associated with it is executed, and the
control is transferred to the statement-x. When all the n conditions become false, the final else default
statement block will be executed.
[email protected]
{
case value-1:
statement block-1;
break;
case value-2:
statement block-2;
break;
...
...
case value-n:
statement block-n;
break;
default:
default statement block;
break;
}
statement-x;
25
Flow chart: Entry
Expressio
n
?
Expression =
Value-1 Statement Block-1
Expression =
Value-2
Statement Block-2
[email protected]
(No match) default Default Statement
Block
Statement-x
In the above, value-1, value-2, ….. are constants or constant expressions and are known as case
labels. Each of these values should be unique within a switch statement. Block-1, Block-2, …. Are
statement lists and they may contain zero or more statements. There is no need to pout braces around
these blocks, but it is important to note that case labels end with a colon (:).
When the switch is executed, the expression value is compared against the values value-1,
value-2, …. If a case is found whose value matches with the expression value, then the statement
block of that case will be executed.
The break statement is an end of the particular case and that is an exit from the switch
statement, transferring the control to the statement-x.
The default is an optional case. It will be executed, if the expression value does not match with
any of the case values.
3. Jumping control statements: The Jumping control statements are classified into four types. They
are,
a. goto
b. break
c. continue
d. return
26
a. goto statement: C-supports the goto statement to transfer the control unconditionally from one
point to another point in the program.
The goto requires a label in order to identify the place where the branch is to be made. A label
is any valid user-defined name and must be followed by a colon (:).
The goto statement can be represented in two ways. They are forward jump and backward
jump.
The Syntax of Forward jump is,
goto label ;
-------
statements; Forward jump
-------
label :
statement;
[email protected]
The Syntax of Backward jump is,
label :
-------
statements; Backward jump
-------
goto label ;
statement;
The goto requires a label in order to identify the place where the branch is to be made. A label
is any valid user-defined name and must be followed by a colon (:).
The goto statement can be represented in two ways. They are forward jump and backward
jump.
The “label :” can be any where in the program that is, either before or after the “goto label ;”
statement. During running of a program when a statement like “goto sample ;” is met, then the flow of
control will jump to the statement immediately following label “sample :”. It happens unconditionally.
Note that a goto statement breaks the normal sequential flow of execution of a program.
If the “label :” is before the “goto label ;” statement then a loop will be formed and the
statements will be executed repeatedly. Such type of jump is called as “Backward jump”.
If the “label :” is placed after the “goto label ;” statement then some statements will be
skipped and that type of jump is called as “Forward jump”.
b. break statement: The break statements are used in switch statements and loops when the break
statement is executed inside a loop then that loop is immediately exited and then the control will be
transferred to the next statement of the following loop.
c. continue statement: It a jumping control statement. It is used in loop control statements. When we
execute the continue statement, then the control goes directly to the test-condition of a loop and it
27
continues the repetition process. By using this continue statement we can repeat the process of
execution in the program.
[email protected]
}
sum = sum + n;
i++;
}
getch( );
}
d. return statement: return statement a jumping control statement. If is used in functions. “return“
is a value that is returned from called function to calling function. It is not possible to return more than
value at a time.
Ex: int fact(int n);
main( )
{
int n ;
clrscr( ) ;
printf(“enter any value = ”);
scanf(“%d”, &n);
printf(“Factorial of a given value = %d”, fact(n));
getch( );
}
int fact(int n)
{
int i, f ;
for( i=1, f=1; i<=n; i++)
{
f = f * i;
}
return( f );
}
4. Loop control statements: The process of repeatedly executing a statement block until the
condition is being true known as Looping.
The C-programming language provides three constructs for performing Loop operations. They are,
28
a. while loop
b. do while loop
c. for loop
a. while loop statement: The simplest of all the looping structures in C is the while statement. The
syntax of while statement is,
Syntax: Initialization;
while (test-condition)
{
Body of loop;
Increment / Decrement;
}
statement-x;
Flow chart:
[email protected]
Start
Initialization
False
Cond Statement-x
?
True
Statement block
Increment / Decrement
In the above, the test-condition is evaluated and if the condition is true, then the body of loop is
executed. After execution, once again the test-condition is evaluated and if it is true, the body of loop
is executed once again. This process of repeated execution continues until the test-condition being
true. If the condition becomes false, then the control is transferred to the statement-x and the loop will
be stop.
b. do while loop statement: The do while loop is a bottom testing loop. It is used to execute the
body of loop at least one time. The syntax of do while statement is,
Syntax: Initialization;
do
{
Body of loop;
Increment / Decrement;
} while (test-condition);
statement-x;
29
Flow chart:
Start
Initialization
Statement block
Increment / Decrement
[email protected]
test-condition is being true. If the condition becomes false, then the control is transferred to the statement-x and
the loop will be stop.
c. for loop statement: The for loop statement is the most popular looping control statement of C-
programming language. The syntax of for loop statement is,
Flow chart:
Start
Initialization
False
Cond Statement-x
?
True
Statement block
Increment / Decrement
2. While loop gets executed as long as the 2. Do while loop also gets executed as long
[email protected]
test-condition is true. as the test-condition is true, but not in the
case of first time execution.
3. In this, the test-condition is evaluated 3. In this, first the body of loop gets
first and the body of loop is executed. executed and then the test-condition is
evaluated.
5. Syntax: 5. Syntax:
Initialization; Initialization;
while (test-condition) do
{ {
Body of loop; Body of loop;
Increment / Decrement; Increment / Decrement;
} } while(test-condition);
statements-x; statement-x;
31
Unit-3
Q: What are the Functions? What are the advantages of Functions? (or)
Explain Function prototype to call with example?
Ans: FUNCTIONS: A function is a re-usable block of code that gets executed on calling. It can be
treated as a sub program. These functions are basically two types. They are,
1. System-defined functions
2. Use-defined functions
[email protected]
The above mathematical functions are System defined functions and are included in
“<math.h>” header files.
2. User-defined functions: The functions which are defined by the user are called as “User-defined
functions”. User can defined any number of functions in a program. For which, “declaration” and
“definition” must be provided.
These User-defined functions can be defined in the sub-program section. The function
definition syntax is as follows,
Structure of a function:
Syntax: return data type function name ( list of arguments )
{
local variable declaration ;
statement block ;
-----
-----
return statement ;
}
Advantages of Functions:
a. It allows re-usability. A function can called any number of times in the main program.
b. It avoids the repetition of calculations in a program.
c. It improves the understandability of a program.
d. It reduces the length of a program code. That is, avoids the re-writing of the same code over and
over.
e. It reduces the complexity of a program.
f. Programs with functions needless maintenance.
g. It performs same set of instructions on different set of data.
32
Ex: int fact(int n); /* function declaration or function prototype*/
main( )
{
int n, x ;
clrscr( ) ;
printf(“enter any value = ”);
scanf(“%d”,&n);
x=fact(n); /* calling function*/
printf(“Factorial of a given value = %d” , x);
getch( );
}
int fact(int n) /* called function or function definition*/
{
[email protected]
int i, f ;
for( i=1, f=1; i<=n; i++)
{
f=f*i;
}
return( f ); /* return statement*/
}
Function declaration or Function prototype: Function declaration gives a clear picture of “return
data type” and “argument type”.
Calling function: It is used to execute the code of a function. Calling function can be “any where in
the program” and “any number of times in the program” while calling a function. It is used to send the
arguments and collect the return values.
Called function or Function definition: It defines the behavior of the function in terms of
instructions. It may include list of arguments, return variable and local variables declaration.
Arguments (Parameters): An argument is a value. That is send from calling function to called
function. It is possible to send any number of arguments from calling function to called function.
These arguments are also called as “Parameters”.
Return statement: “return” is a keyword in our C-language. This “return” statement is used to return
a value from called function to calling function. It is possible to return more than one value at a time
from called function to calling function.
When a function does not return any value then we can write return data type as “void”. When
a function returns something then we can write return data type.
33
Q: Explain why we are using the functions?
Ans: Reasons for using the functions: A function is a re-usable block of code that gets executed on
calling. It can be treated as a sub program.
There are two reasons to use functions. They are,
1. By using functions “avoids rewriting of the same program code over and over”:
Suppose we have a program code in our main program that is used to calculate the factorial of
a given number. If we want to print a Pascal triangle then we don’t like to write same factorial
program code again and again. Instead of this we prefer to jump to a “program code” that calculates
factorial of a given number and then jump back to the main program. This “program code” is known
as a function.
2. Using functions “it becomes easier to write programs and improves the understandability”:
[email protected]
If the operation of a program can be divided into separate activities and each activity placed in
a different function. Then each could be written and checked independently and separating the
program code into modules. “Functions” make the program easier to design and it improves the
understandability.
1. With arguments and with return value: A function that takes arguments and returns a
value is known as a “function with arguments and return value”.
[email protected]
return(n);
}
Arguments matching between the Called function and Calling function
When a function has arguments, then it receives the data from the calling function. Similarly,
when called function returns a value then the calling function receives the data from the called
function. Note that, there is a data transfer between the calling function and the called function. This is
a Two-way data communication between the functions.
Ex: int fact (int);
main( )
{
int x, n;
clrscr ( );
printf (“Enter any number = ”);
scanf (“%d”, &n);
printf (“Factorial of a given number = %d”, fact (n));
getch( );
}
int fact (int n)
{
int i, f;
for (i=1, f=1; i<=n; i++)
{
f=f*i;
}
return (f);
}
2. With arguments but no return value: A function that takes arguments but not returns a
value is known as a “function with arguments but no return value”.
35
main( ) function-1 ( datatype var_name)
{ {
------ value of args ------
------ ------
function-1 (a); no return value }
------
------
}
[email protected]
{
------
function-1 (a1, a2, . . . . . , an); /*calling function*/
------
}
return data type functioin-1 (data type x1, data type x2, ……., data type xn) /*called function*/
{
------
}
Arguments matching between the Called function and Calling function
When a function has arguments, then it receives the data from the calling function, but called
function does not return a value and the calling function does not receive any data from the called
functions. This is a One-way data communication between the functions.
main( ) function-1 ( )
{ {
------ No input ------
------ ------
function-1 ( ) ; function return (n);
------ returning value }
}
One-way communication between the functions
The nature of data communication between calling function and called function is with out arguments
but returns a value.
[email protected]
main( )
{
------
function-1 ( ); /*calling function*/
------
}
return data type functioin-1 ( ) /*called function*/
{
------
return ( n );
}
Arguments matching between the Called function and Calling function
When a function has no arguments, then it does not receive any data from the calling function,
when a called function returns a value then the calling function receives the data from the called
function. This is a One-way data communication between the functions.
Ex: int fact ( );
main( )
{
clrscr ( );
printf (“Factorial of a given number = %d”, fact ( ));
getch( );
}
int fact ( )
{
int i, f, n;
printf (“Enter any number = ”);
scanf (“%d”,&n);
for (i=1, f=1; i<=n; i++)
{
f=f*i;
}
return ( f );;
}
37
4. No arguments and no return value: A function that does not take any arguments and does not
return any value is known as a “function with no arguments and no return value”.
main( ) function-1 ( )
{ No input {
------ ------
function-1 ( ) ; no return value }
------
}
No data communication between the functions
The nature of data communication between calling function and called function is with no
arguments and no return value.
main( )
[email protected]
{
------
function-1 ( ); /*calling function*/
------
}
return data type functioin-1 ( ) /*called function*/
{
------
}
Arguments matching between the Called function and Calling function
When a function has no arguments, then it does not receive any data from the calling function.
Similarly, when the called function does not return a value and then the calling function does not
receive any data from the called function. In this, there is no data communication between calling
function and called function. Note that, there is only a transfer of control but not the data.
Ex: void fact ( );
main( )
{
clrscr ( );
fact (n);
getch( );
}
void fact ( )
{
int i, f, n;
printf (“Enter any numbe = ”);
scanf (“%d”, &n);
for (i=1, f=1; i<=n; i++)
{
f = f * i;
}
printf (“Factorial of a given number = %d”, f );
}
38
Q: What are Parameter passing techniques in ‘C’? Explain with examples.
Ans: Parameter passing techniques: The techniques which are used to pass the parameters from
calling function to called function are known as “Parameter passing techniques”.
1. Call by value
2. Call by reference
1. Call by value: In this technique, we can send the values from actual arguments to formal
arguments. That is, the actual argument value is assigned to formal argument from calling function to
called function. Here, the arguments are also called as parameters.
In this technique, if there are any modifications on formal arguments then there is no change
[email protected]
on actual arguments.
Ex: void swap(int, int);
main( )
{
int a =10, b = 20;
clrscr( );
printf(“Before swapping a = %d, b = %d”, a, b);
swap(a, b); /* here a, b are actual arguments */
printf(“After swapping a = %d, b = %d”, a, b);
getch( );
}
void swap(int x, int y) /* here x, y are formal arguments */
{
int t;
t = x;
x = y;
y = t;
}
In the above example, the output is a = 10, b = 20. It does not change the value of ‘a’ and ‘b’.
Because the initial value of ‘a’ and ‘b’ are 10, 20 respectively. We are sending ‘a’ & ‘b’ values to ‘x’
and ‘y’ from calling function to called function. That is, x = a and y = b. Therefore, values of x and y
are 10 & 20 respectively.
In the swap( ) called function, the x and y values are replaced from x to y, and y to x. But ‘a’
and ‘b’ values are not replaced in the main function section. Because, in the above example we used
parameter passing technique is “call by value”. Therefore, the values of ‘a’ and ‘b’ are not swapped.
39
2. Call by reference: In this technique, we can send the address of actual arguments to formal
arguments. That is, the actual argument address is assigned to formal argument. In this case, the
corresponding formal argument must be the pointer variable.
In this technique, if there are any modifications on formal arguments then there is
automatically change on actual arguments.
[email protected]
printf(“Before swapping a = %d, b = %d”, a, b);
swap(&a, &b);
printf(“After swapping a = %d, b = %d”, a, b);
getch();
}
void swap(int *x, int *y)
{
int t;
t = *x;
*x = *y;
*y = t;
}
In the above example, the output is a = 20, b = 10. It changes the value of ‘a’ and ‘b’. Because
the initial value of ‘a’ and ‘b’ are 10, 20 respectively. We are sending ‘a’ & ‘b’ addresses to the ‘x’
and ‘y’ from calling function to called function.
Here, the formal arguments ‘x’ and ‘y’ are pointer variables. That is, ‘x’ and ‘y’ contained the
address of ‘a’ and ‘b’.
Modifications on ‘x’ and ‘y’ in the called function means ‘a’ and ‘b’ modifications in the
calling function. Because, we are doing the modifications of ‘x’ and ‘y’ by using the addresses of ‘a’
and ‘b’ i.e., by using call by reference. Therefore, the values of ‘a’ and ‘b’ are swapped in the main
function section.
40
Q: What are the Recursive functions? Explain. (or) What is Recursion? Explain with example.
Ans: Recursion: If the function is called within the same function is known as Recursion.
In Recursion, a function is called within the same function till meets with a proper terminating
condition.
The best example of using a Recursion function is to find the factorial of a given number as
follows,
Ex: int fact(int n);
main( )
{
int n ;
clrscr( ) ;
printf(“enter any value = ”);
scanf(“%d”,&n);
[email protected]
printf(“Factorial of a given value = %d”,fact(n));
getch();
}
int fact(int n)
{
int i, f ;
if (n= =0 || n= =1 )
{
return ( 1 );
}
else
{
f=n*fact (n-1);
return ( f );
}
}
In the above example, assume n=4, since the value of ‘n’ is not ‘0’ or ‘1’ then the else
statement f = n*fact (n-1) will be executed.
Ex: n=4
f = 4 * fact (3)
= 4 * 3 * fact (2)
= 4 * 3 * 2 * fact (1)
= 4*3*2*1
f = 24
When we write recursive function, we must use “if statement” otherwise the function will never
returns the value.
41
Q: What are Arrays in ‘C’? And explain the advantages and disadvantages of Arrays?
Ans: ARRAY: An Array is a variable. It is used to store the group of data values of similar data type.
Array elements (values) share common name and these are stored in sequential memory locations. To
refer the elements of an array, then we can use the indexes accordingly. Array indexing starts from ‘0’
and ends with one less than the size.
Array can be divided into two types. They are,
One-Dimensional Array
Multi-Dimensional Array
Declaration of Arrays: Like other variables, arrays must be declared before they used.
Syntax: Datatype array_variable_name [maximum_size];
[email protected]
In the above syntax,
The data type specifies the data type of the elements such as int, float or char.
The variable_name specifies the array name.
The maximum_size indicates the maximum number of elements that can be stored inside the
array.
Array declaration and initialization: Array declaration and initialization can be done as,
int a[4] = {10, 20, 30, 40};
For example, to access the third element of an array, we may use ‘2’ as an index.
Advantages of Arrays:
1. It is able to store many elements at a time.
2. It allows random access of elements that is any element of an array using indexes.
Dis-advantages of Arrays:
1. Pre-determining the size of an array is must.
2. Memory wastage will be there.
3. To search or delete an element of an array we need to check throughout the array.
42
Q: Explain about different types of Arrays?
Ans: ARRAY: An Array is a variable. It is used to store the group of data values of similar data type.
Array elements (values) share common name and these are stored in sequential memory locations. To
refer the elements of an array, then we can use the indexes accordingly. Array indexing starts from ‘0’
and ends with one less than the size.
Array can be divided into two types. They are,
1. One-Dimensional Array
2. Multi-Dimensional Array
1. One-Dimensional Array:
A list of elements can be given with one variable name using only one subscript and such type
[email protected]
of variable is called as a Single subscript (or) One-dimensional array.
One-dimensional array can be represented either “one row with number of columns” or “one
column with number of rows”.
2. Multi-Dimensional Array:
Multi-dimensional arrays are used to represent the data in the form rows and columns. That is
by taking more than one subscript.
Two-dimensional array: A list of elements can be given with one variable name using two
[email protected]
subscripts. And such type of variable is called as “Two subscripts variable” or “Two-dimensional
array”.
In Two-dimensional array the data is arranged in the form of rows and columns.
The C-programming language allows the array of ‘3’ or ‘more’ dimensions. If it is an array
with 3 subscripts, then it is called as a Three-dimensional array.
[email protected]
Ex: i). int survey [2] [3] [4];
ii}. float table [5] [4] [5] [3];
Where, ‘survey’ is a 3-dimensional array variable. It contains 120 integer type elements. And
‘table’ is a 4-dimensional array variable. It contains 300 float type elements.
Q: What is Searching? Explain the methods that are used for searching?
Ans: Searching: Searching is a technique used to verify whether an element is present in the list or
not. To search for an element, there are several methods such as,
1. Linear search
2. Binary search
1. Linear search: This is also called as Sequential search. In this we compare the elements of an
array sequentially till the end of an array.
Ex: main( )
{
int a[4] = {10, 5, 6, 8}, i, k, found=0;
clrscr( );
printf(“\nGiven Array = “);
for(i=0; i<4; i++)
{
printf(“%4d”,a[i]);
}
printf(“\nEnter any value to be search = “);
scanf(“%d”,&k);
for(i=0; i<4; i++)
{
if(a[i] = = k)
{
printf(“\nValue found at %d location”,i+1);
45
found=1;
break;
}
}
if(found = = 0)
{
printf(“\nValue not found”);
}
getch( );
}
In the above example, if we search for ‘6’, then output must be “Value found at 3 location”. If
we search for ‘9’, then output must be “Value not found”.
2. Binary search: Binary search is also called as Logarithmic search. Binary search can be
performed on sorting elements only that is either ascending or descending order.
[email protected]
In this search, it involves a method of splitting. The set of elements split into two halves and
splitting lower set (if element falls lower side) or upper set (if element falls upper side) repeated by till
an element is found.
Ex: main( )
{
int a[5] = {2, 4, 3, 1, 5}, i, k, found=0, f, l, m, j, t;
clrscr( );
for(i=0; i<4; i++)
{
for(j=i+1; j<5; j++)
{
if(a[i] > a[j])
{
t = a[i];
a[i] = a[j];
a[j] =t;
}
}
}
printf(“\nGiven Array = “);
for(i=0; i<5; i++)
{
printf(“%4d”, a[i]);
}
printf(“\nEnter any value to be search = “);
scanf(“%d”,&k);
f = 0;
l = 4;
while (f <= l)
{
m = (f+l)/2;
if(a[m] = = k)
46
{
printf(“\nValue found at %d location”, i+1);
found=1;
break;
}
else if(a[m] > k)
{
l = m-1;
}
else
{
f = m+1;
}
}
if(found = = 0)
{
[email protected]
printf(“\nValue not found”);
}
getch( );
}
In the above example, the array size is ‘5’ and the middle address of the given array is ‘2’.
Assume the search element is ‘4’, and then the output must be “Value found at 4 location”.
Otherwise output must be “Value not found”.
[email protected]
Ex: main( )
{
int a[2] = {1, 2}, b[3] = {4, 5, 6}, c[5], i;
clrscr ( );
for ( i = 0; i<2; i++ )
{
c[i] = a[i];
}
for ( i = 0; i<3; i++ )
{
c[2+i] = b[i];
}
printf(“\nAfter Merging = “);
for(i=0; i<5; i++)
{
printf(“%4d”, c[i] );
}
getch( );
}
In the above example, the above two arrays merged into third array. After merging this program
prints the merged elements would be 1 2 4 5 6.
Q: Explain arrays as arguments? (or) Explain array as an argument passing through a function?
(or) Explain functions with arrays with the help of suitable example?
Ans: Arrays as arguments: An array can be send to the functions as an argument while calling a
function. With this technique it is possible to send many values at a time. When we do some
modifications to array variables in the functions, it changes the original values also.
Ex: void disp(int [ ], int);
main( )
{
int a[4] = {1, 2, 3, 4};
48
clrscr();
disp(a, 4);
getch();
}
void disp(int a[4], int n)
{
int i;
for( i=0; i<n; i++ )
{
printf(“%4d”, a[i]);
}
}
In the above example, array ‘a’ is send to the called function disp( ) as an argument, then the
called function disp( ) prints all the values of an array that are collected in the local array ‘a’.
In multi-dimensional arrays, they can by send to the functions as arguments while calling a
[email protected]
function. With this technique, it is possible to send many values at a time in the form of rows and
columns. When we do some modifications to array variables in the functions, it changes the original
values also.
Q: What is a String? How it is used in C – Language and explain the operations on strings with
examples?
49
Ans: String: String is a set of characters of one dimensional array and of character data type. That is
in other words, the string is an array of characters and it is a one dimensional array of character data
type. Every string is terminated by null character (‘ \0 ’).
The string variable declaration syntax is,
In the above declaration s[10] creates a string with 9 or less than 9 characters.
A string variable is a filled array of characters. The index starts with zero and ends with less
than one size of the array. Note that, a string variable automatically places a special symbol ‘\0’ (null
character) in the array immediately after the last character of the string. If the string size is less than
the declaration size, then the rest of the characters will be free.
[email protected]
A string can be initialized in two different ways.
For example: char s[ ] = { ‘s’, ‘r’, ‘e’, ‘e’, ‘t’, ‘a’, ‘n’ };
char s[ ] = “sreetan”;
Operations on strings:
The string operations in C – Language are,
1. Reading a string from terminal
2. Writing a string to be retuned
3. Copying a string
4. String handling
5. Table of strings
50
1. Reading a string from terminal:
There are two methods to read a string from terminal. They are,
a. Reading a word
b. Reading a line of text
a. Reading a word: The input statement scanf( ) can be used with “%s” conversion character
(format specification) to read a string of characters. But by using “%s” conversion character in
scanf( ), we can read only one word.
Reading series of words by using scanf( ) as,
main( )
{
char s1[10], s2[10], s3[10];
clrscr( );
[email protected]
printf(“enter any 3 series of words = “);
scanf(“%s%s%s”, s1, s2, s3);
printf(“%s\n%s\n%s”, s1, s2, s3);
getch( );
}
b. Reading a line of text: We can read only one word from the terminal by using scanf(). When
we want enter the space at the time of reading the text, then the scanf( ) will terminate the input.
Using getchar( ) repeatedly to read single characters from the input and place them into
character array. When the new line character (‘\n’) is entered, then input is terminated and null
character (‘\0’) is inserted automatically at the end of the string.
Ex: To Read a line of text:
main( )
{
char s[20], ch;
int i;
clrscr( );
printf(“enter any line of text :\n”);
i=0;
while((ch=getchar( ))!=’\n’)
{
s[i] = ch;
i = i +1;
}
s[i] = ’\0’;
printf(“%s”, s);
getch( );
}
2. Writing a string to be returned:
51
The printf( ) can be used with ‘%s’ format specification to print a string of characters on the
screen. So, the ‘%s’ format specification is used to display the array of characters and it is terminated
by the null (’\0’) character.
Ex: printf(“%s”, s);
The above statement is used to display the string entered in the array ‘s’.
3. Copying a string:
We cannot assign directly one string to another string. We cannot combine two strings together
by the simple arithmetic addition.
Ex: Copy of string to another string:
main( )
{
char s1[10], s2[10];
[email protected]
int i;
clrscr( );
printf(“enter any string = “);
scanf(“%s”, s1);
for(i=0; s1[i]!=’\0’; i++)
{
s2[i] = s1[i];
}
s2[i] = ’\0’;
printf(“Copied string = %s”, s2);
getch( );
}
4. String handling:
The standard string handling functions in C – Language are,
a. strlen( )
b. strcpy( )
c. strrev( )
d. strcmp( )
e. strcat( )
f. strlwr( )
g. strupr( )
a). strlen( ): It returns length of a given string. That is used to count the number of characters in a
string.
Syntax: variable = strlen(string_variable);
Where, variable is an integer variable to store the count of number of characters of a given string.
Ex: n = strlen(“sreetan”);
52
Here n is 7.
b). strcpy( ): It is used to copy the string from one string variable to another string variable.
Syntax: strcpy(destination_string, source_string);
Ex: strcpy(s2, s1); /* The characters of s1 copied to s2. */
s1 s2 string function s1 s2
“good” “bad” strcpy(s2, s1) “good” “good”
“sam” “ram” “sam” “sam”
[email protected]
s string function s
“sam” strcpy(s2, s1) “mas”
“madam” “madam”
d). strcmp( ): It is used to compare the given strings. It returns the comparison value.
Syntax: strcmp(string1, string2);
Ex: strcmp(s1, s2);
If the return value is zero, then both the strings are equal. If the return value is greater than
zero, then string1 is greater than string2. if the return value is less than zero, then string1 is less than
string2.
[email protected]
Before execution of s string function After execution of s
“sreeram” strupr(s) “SREERAM”
“Abhiram” “ABHIRAM”
“RAGHURAM” “RAGHURAM”
5. Table of strings:
A list of strings can be treated as “table of strings”.
Table of strings can be represented using two-dimensional array of character data type.
Ex:char s[10][10];
In the above example, first size ‘10’ indicates the maximum number of strings and second
size ‘10’ indicates the maximum number of characters in each string.
To print the table of strings as,
Ex: for( i=0; i<n; i++ )
{
printf(“%s\n”, s[i]);
}
54
Unit-4
Q: what are the Pointers and explain the advantages and disadvantages?
Ans: POINTERS: Pointers are other important features of C-Language. Pointer is a variable. It is
used to store the address of another variable and prints the value in that address.
The declaration of Pointer variable is,
Advantages of pointers:
1. Pointers increase the program execution speed.
[email protected]
2. Pointers improve the efficiency of the program.
3. Pointers reduce the length of and complexity of the program.
4. Pointer allows call by reference mechanism for arguments.
5. Pointer allows dynamic memory allocation.
Dis-advantages of pointers:
1. Pointer variable requires extra memory.
2. Programmer finds writing pointers tiresome.
Let us consider,
int a=10;
Here, ‘a’ is a variable name. ‘&a’ is the address of variable and ‘10’ is the value of variable.
Ex: main( )
{
clrscr( );
b=&a;
getch( );
55
Memory Organization
65535
[email protected]
a vari abl e a vari abl e 10 value
` 10 val ue
65224 address *b poi nt er vari abl e address
65224
65226
R epresent at i on of a vari abl e R epresent i ng poi nt er as a vari abl e
Advantages of pointers:
1. Pointers increase the program execution speed.
2. Pointers improve the efficiency of the program.
3. Pointers reduce the length of and complexity of the program.
4. Pointer allows call by reference mechanism for arguments.
5. Pointer allows dynamic memory allocation.
Pointer arithmetic:
Pointer arithmetic is one of the powerful features of C-language. If the variable ‘p’ is a pointer
variable, then as well as ‘p+1’ is also a pointer variable and it gives the address of next location of a
56
variable of same data type. This mechanism is known as “pointer arithmetic”. It is used in accessing
array elements using pointers.
Ex: main( )
{
int a[ ]={1, 2, 3, 4}, *p;
clrscr( );
p=&a[0];
printf(“%d\n”, *p); /* It prints 1 */
p=p+1; /* It is a pointer arithmetic */
printf(“%d”, *p); /* It prints 2 */
getch( );
}
[email protected]
A: * operator: The ‘*’ operator is used to point to an address of variable to fetch the value of
variable. We call ‘*’ as pointer. Consider the following example,
int *a;
int b = 20;
a = &b;
printf(“%d”,*a);
In the above example, that prints the value 20. Here ‘a’ is a pointer variable that holds the
address of the variable ‘b’, and pointing to that gives the value of ‘b’ that is 20.
We use any number of pointers in the case of multiple pointers as in the following example.
int *a1, **a2, ***a3;
int b = 20;
a1 = &b;
a2 = &a1;
a3 = &a2;
printf(“%d”, ***a3); /* prints 20 */
& operator: The ‘&’ operator is used to refer an address of a variable. Every variable has some
address for storing its value there. Consider the following example,
int b = 20;
printf(“value =%d”,b); /* prints the value */
printf(“%u”, &b); /* prints the address*/
In the above example, we have used ‘&’ operator to refer the address of the variable b.
[email protected]
They are,
1. malloc( )
2. calloc( )
3. free( )
4. realloc( )
Ex: #include<stdio.h>
#include<stdlib.h>
#include<conio.h>
main( )
{
int *ptr;
int n, i;
clrscr( );
n=5;
ptr = (int *) malloc (n * sizeof(int) );
if(ptr==NULL)
{
pritnf(“\nMemory not allocated”);
}
else
{
printf(“\nMemory allocated successfully”);
for(i=0; i<n; i++)
{
58
ptr[i] = i+1;
}
printf(“\nThe Array Elements:”);
for(i=0; i<n; i++)
{
printf(“%4d”, ptr[i] );
}
}
getch( );
}
2 calloc( ): ‘calloc( )’ or ‘contiguous allocation’ method is used to dynamically allocate the
specified number of blocks of memory of the specified type. It initializes each block with a
default value ‘0’.
Syntax: ptr = (cast-type *) calloc (n, element-size);
[email protected]
Example: ptr = (int *) calloc (10, sizeof(int) );
3 free: ‘free( )’ method is used to dynamically de-allocate the memory. The memory allocated
using functions malloc( ) and calloc( ) are not de-allocated on their own. Hence the free( )
method is used, whenever the dynamic memory allocation takes place. It helps to reduce
wastage of memory by freeing it.
Syntax: free(ptr);
datatype member-n;
};
struct structure_name variable_name;
1. The structure declaration starts with a keyword “struct” along with the structure name.
59
2. A structure name indicates the name of the structure.
3. The members in a structure between opening and closing brace of the structure.
4. The closing brace of the structure must be end with a semi colon(;).
5. The declaration of a structure type variable is,
struct structure_name variable_name;
6. The syntax of accessing the member of a structure using structure variable is,
variable_name.member
[email protected]
Ex: struct student
{
int rno;
char name[10];
int marks;
};
struct student s;
In the above example, structure name is “student” and it contains rno, name, marks are the
members of a structure.
Advantages of Structures:
1. Handling many data types at a time.
2. Using structures to return more data values grouped together. 60
3. It reduces the burden of the program.
4. Structures can include other structures to extend its feature.
[email protected]
{
datatype member-1;
datatype member-2;
datatype member-n;
};
union union_name variable_name;
The union sample variable ‘s’ size is 4 bytes. Because the maximum size of the member is ‘b’
has 4 bytes.
c = 1 byte
c a = 2 bytes
a b = 4 bytes
b
61
Q: Compare structures and unions with syntax and examples?
Ans:
STRUCTURES UNIONS
[email protected]
variables are accessed with are accessed with ( .) operator.
(.) operator.
7. Syntax: 7. Syntax:
struct structure_name union union_name
{ {
datatype member-1; datatype member-1;
datatype member-2; datatype member-2;
8. Example: 8. Example:
struct sample union sample
{ {
int a; int a;
float b; float b;
char c; char c;
}; };
struct sample s; union sample s;
62
Q: Explain the uses of arrays as structure members and array of structure?
Ans: STRUCTURE: Structure is a collection of data items of different data types using a single
name. It is a secondary data type and it is also called as user-defined data type.
The syntax of structure is,
Syntax: struct structure_name
{
datatype member-1;
datatype member-2;
datatype member-n;
};
struct structure_name variable_name;
[email protected]
Example: struct emp
{
int eno;
char ename[10];
float basic;
};
struct emp e[10];
Array of structure members:
In the above example, eno, ename, and basic are the members of an ‘emp’ structure. In that
ename is a character data type of one dimensional array. Because ename is a string. Therefore, ename
is an array as structure member in an emp structure.
Array of structures:
For example, the salaries of number of employees in a company. We describe employee eno,
ename, basic and then declared all the employees as structure variables. In such cases, we may
declared an array of structures and each element of the array representing a structure variable.
Example:
Struct emp
{
int eno;
char ename[10];
float basic;
};
struct emp e[2]={{123, “sam”, 22000}, {234, “ram”,28000}};
In the above example, it declares the structure variable ‘e’ as an array of two elements. They are e[0]
and e[1] and initialized their member as,
e[0].eno = 123;
e[0].ename = “sam”;
63
e[0].basic = 22000;
e[1].eno = 234;
e[1].ename = “ram”;
e[1].basic = 28000;
In the above example, in the above entire array of structure can be printed as follows,
for( i=0; i<2; i++)
{
printf(“%d\n%s\n%f”, e[i].eno, e[i].ename, e[i].basic);
}
[email protected]
type is used for declaring string constants with integer equalent values.
By using the Enumeration, programmer can write strings in the form of integers. This data type
can be defined using the keyboard “enum”.
member-n
};
enum enumeration_name list of variables;
Example: #include<stdio.h>
main( )
{
enum colors
{
Red,
Green,
Blue
};
enum colors r, g, b;
clrscr( );
r=Red;
g=Green;
b=Blue;
printf(“%d\n%d\n%d”, r, g, b);
getch( );
}
64
Unit-5
Object-Oriented Programming Paradigm:
C++ is an Object-Oriented Programming Language. It was developed by Bjarne
Stroustrup at AT & T Bell Laboratories in Murray Hill, New Jersey, USA, in the early 1980’s.
The major objective of object-oriented approach is to eliminate some of the drawbacks
faced in the procedural approach.
Object-oriented programming ties data more closely to the functions and protects it
from unintentional modifications by other functions.
Object-oriented programming allows programmers to split a problem into a number of
entities called objects and then build data and functions around these entities.
The combination of data and functions make up an object.
Function Function
Data
Function Function
Object A Object B
Data Data
Communication
Functions Functions
Object C
Functions
Data
Include files
Class declaration
[email protected]
Include files: It is a Link section. It includes the header files. This section is used to provide
instructions to the C++ compiler to link the functions to the C++ system library.
Ex: #include<math.h>
#include<string.h>
#include<iostream.h>
Class declaratios: A C++ program may contain multple class defnitons. The usage of number of classes
depends on the complexity of the program.
Classes contain data members and member functons that operate on the data members of the class.
Member functons may contain data type declaratons and executable statements.
Member functions definitions: A member function is the basic unit of functionality contained in
a class. It contains the set of executable statements that can be applied to specific object of a class.
66
is an input statement in C++. In the above statement, cin is a predefined object in C++ that
corresponds to the standard input stream. The standard input stream is Keyboard.
The operator >> is known as extraction or get from operator. It takes the value from the
keyboard and assigns it to the variable on its right.
----------
----------
Keyboard
Input using Extraction Operator
[email protected]
Output statement: The statement which is used to take an output from the computer is known as
Output statement.
The statement
is an output statement in C++. In the above statement cout is a predefined object in C++ that
corresponds to the standard output stream. The standard output stream is Monitor screen.
The operator << is known as insertion or put to operator. It inserts the contents of the variable
on its right to the object on its left.
Screen
67
b) What will be the Initial value of the variable if the value is not assigned (that is, the
Default initial value).
c) What is the Scope of the variable (that is, in which function the value of a variable would
be available).
d) What is the Life of the variable (that is, how long the variable would exist).
Therefore, to explain the behavior of the variable there are 4 Storage classes in our C-Language.
They are,
[email protected]
1. Automatic storage class: The keyword for this storage class is “auto”. Automatic storage
class is the default storage class for all local variables. This variable gets initialized or
recreated each time when a function is called.
2. Register storage class: The keyword for this storage class is “register”. For Register storage
class variables, system locates memory in CPU registers. This is done for fast accessing.
Because, the speed of the CPU register is high. Register storage class can be applied to local
variables only.
68
Storage location : CPU Registers
Default initial value : Some Garbage value
Scope : Local to the block, that is in which the variable is defined
Life : Till the control continues with in the block, that is in which the
variable is defined
Note: Register storage class variables do not have any address.
[email protected]
Output: 0 0 0
Generally the CPU registers in a micro computer are usually 16-bit registers and therefore,
they cannot hold a float value or double value. Because, float value requires 4-bytes and
double value requires 8-bytes. However, if we use above declarations, then we won’t get any
error messages. The compiler would treat all the variables to be of automatic storage class.
3. Static storage class: The keyword for this storage class is “static”. A static variable can be
initialized for only once. A static variable also gets initialized to ‘0’ (zero) automatically.
void sample( )
{
static int a;
cout<<a;
a++;
}
Output: 0 1 2
69
In the first example, when the variable ‘a’ is ‘auto’, each time sample( ) is called and it is
reinitialized to ‘0’. When the function terminates, ‘a’ vanishes and its new value ‘1’ is lost.
That is why ‘a’ is initialized to ‘0’ every time and prints ‘0’.
In the second example, when the variable ‘a’ is ‘static’ each time sample( ) is called and it
is incremented by ‘1’. When the function terminates, ‘a’ increments and its new value ‘1’ is
assigned and also prints that incremented value.
4. External storage class: The keyword for this storage class is “extern”. This is a storage class
for all Global variables. Other programs can also share extern variable. External storage class
variables get initialized to ‘0’ (zero) automatically.
Storage location : Memory
Default initial value : Zero
[email protected]
Scope : Global
Life : As long as the programs execution does not come to an end
(that is through out the program)
In the above program, that prints the values of ‘a’ variable to the function increment( ). Since,
‘a’ has been declared outside of all the functions. Here, ‘a’ is a global variable of an external
storage class.
70
Q: Explain about Local and Global variables with examples?
A: Local Variables:
1. Automatic storage class type variables are called as Local variables.
2. Local variable does not take any initial value. It takes the garbage value.
3. Scope of the Local variable is within the function.
4. Life of the Local variable is till the control continuous within the functions.
Ex: #include <iostream.h>
#include <conio.h>
void main( )
{
clrscr( );
auto int a=1;
{
[email protected]
auto int a=2;
{
auto int a=3;
cout<< a <<endl;
}
cout<< a <<endl;
}
cout<< a;
getch();
}
Output: 3 2 1
Global Variables:
1. External storage class type variables are called as Global variables.
2. Global variable automatically gets initialized to ‘0’ (zero).
3. Scope of the Global variable is throughout the program.
4. Life of the Local variable is till the program is terminated.
Ex: #include<iostream.h>
#include<conio.h>
void increment( );
int a;
void main( )
{
clrscr( );
cout<< a<<”\t”;
increment( );
increment( );
a++;
cout<<a<<”\t”;
getch( );
}
71
void increment( )
{
a++;
cout<< a << ”\t”;
}
Output: 0 1 2 3
[email protected]
Scope of the local variable is within the Scope of the global variable is throughout the
function. program.
Life of the local variable is till the control Life of the global variable is till the program is
continuous within the function. terminated.
Ex: Ex:
#include <iostream.h> #include<iostream.h>
#include <conio.h> #include<conio.h>
void increment( );
void main( )
{ int a;
clrscr( ); void main( )
auto int a=1; {
{ clrscr( );
auto int a=2; cout<< a<<”\t”;
{
increment( );
auto int a=3;
cout<< a <<endl; increment( );
} a++;
cout<< a <<endl; cout<<a<<”\t”;
}
getch( );
cout<< a;
}
getch( );
void increment( )
} {
Output: 3 2 1 a++;
cout<< a << ”\t”;
}
Output: 0 1 2 3
[email protected]
C is a procedural language; whereas C++ is an object-oriented language.
C is a weak language, whereas C++ is a strong, unsafe and nominative language.
C is designed by Dennis Ritchie; whereas, C++ is a product of Bjarne Stroustrup.
C influences awk, csh, C++, C#, Objective-C, BitC, D, Concurrent C, Java, JavaScript, Limbo,
Perl, PHP; whereas, C++ influences Ada 95, C#, Java, PHP, D, Aikido.
C is influenced by B (BCPL,CPL), ALGOL 68, Assembly; whereas, C++ is influenced by C,
Simula, Ada 83, ALGOL 68, CLU, ML.
C was proposed in 1972; whereas C++ appeared in 1985.
Garbage Collection is manual in C and allows better memory management; whereas no
Garbage Collection is available in C++ standard library.
C programs are faster to compile and execute than C++ programs.
C has .c file extension; whereas, C++ files have .cpp extension.
C has no native string datatype; but C++ sports it as array, std::string.
C uses struct; whereas C++ uses both class and struct.
C uses scanf() and printf() for input and output respectively; whereas, C++ uses cin and cout
for input and output purpose.
C does not allow generic programming; but C++ allows it.
C does not allow meta programming; but C++ allows it.
1. Objects
2. Classes
3. Data Encapsulation
4. Data Abstraction
5. Information Hiding
6. Inheritance
7. Polymorphism
8. Dynamic binding
9. Message communication
[email protected]
They may represent a person, a place, a bank account, a table or any item. They may also
represent user-defined data types such as vectors and lists.
When a program is executed, the objects interact by sending messages with each other.
For example, if “customer” and “account” are two objects in a program, the customer object
may send a message to the account object requesting for the bank balance. Each object
contains data and code to manipulate the data. Objects can interact each other, but without
knowing the details of each other’s data or code.
Object: EMPLOYEE
DATA
EName
EmpNo
Basic
FUNCTIONS
itax( )
gsal( )
netsal( ) Representation of an Object
Data
Information “in” and Information “out”
Functions
[email protected]
The data types created by the data abstraction process are known as Abstract Data
Types (ADT). It describes the objects in terms of behavior, but without including background
details.
5. Information Hiding: Objects have the property Information hiding. It helps the
programmer to build the security of programs. Implementation details (background details) are
hidden with the objects themselves.
6. Inheritance: The process of reusing the existing properties of existed resources
is known as Inheritance. That is, to reuse the properties of Base class in Derived class.
Inheritance supports the concept of Hierarchical classification.
Parent features
Child class Derived or sub class
Child features
7. Polymorphism: Polymorphism means the ability to take more than one form.
Different behaviors of functions (or) operators (or) objects at different situations called as
Polymorphism. For example: The behavior depends upon the types of data used in the
operation.
75
8. Dynamic binding: Binding refers to the linking of a procedure call to the code
to be executed in response to the call. Dynamic binding means that the code associated with a
given procedure call is not known until the time of the call at runtime. It is associated with
polymorphism and inheritance. A procedure call associated with a polymorphic reference
depends on the dynamic type of that reference.
[email protected]
Q: What is a class? Explain the properties of a class.
A: Class: The most important feature of C++ is the class. It is an extension idea of structure in C-
language. Structure does not providing any security for the members and structure does not include
any member functions in C-language.
A class is a keyword and it is a collection of data members and member functions. A class is
an extension of the structure data type. And this class is used to create User-defined data types (or)
Abstract data types.
When defining a class, we are creating a new abstract data type that can be treated like any
other built-in data type. Generally, a class specification has two parts:
1. Class declaraton
2. Class functon defnitons
The class declaration describes the type and scope of its members. The class function
definitions describe how the class functions are implemented.
class class_name
{
private:
variable declarations;
function declarations;
public:
variable declarations;
function declarations;
};
The class declaration is similar to a struct declaration. The keyword class specifies that, what
follows is an abstract data of type class_name. The body of a class is enclosed within braces and
terminated by a semicolon (;).
76
The class body contains the declaration of variables and functions. These variables and
functions collectively called class members. They are usually grouped under two sections, namely,
private and public to denote which of the members are private and which of the members are public.
The keywords private and public are known as Access modifiers (Visibility labels). Note that these
keywords are followed by a colon (:).
The class members which are declared as private can be accessed only from within the class.
The class members which are declared as public can be accessed from outside the class also.
The data hiding is the key feature of object-oriented programming using private declaration.
The use of the private keyword is optional. By default, the members of a class are private. That is, if
we are not using any access modifier, by default, then all those members are private. Such a class is
completely hidden from the outside world and does not serve any purpose.
The variables declared inside the class are known as data members and the functions are
[email protected]
known as member functions. Only the member functions can have access to the private data members
and private functions. However, the public members (both data and functions) can be accessed from
outside the class.
The binding of data and functions together into a single class-type variable is referred as
Encapsulation.
CLASS
No entry to private area Private area
X
Data
Functions
Public area
Functions
[email protected]
4. Data members are declared as private.
5. Member functions are declared as public.
6. Private members cannot be accessed outside the class.
7. Public members can be accessed within the class and outside the class.
8. Member functions can be overloaded.
9. A class can be written in another class.
10. Member functions can take objects as arguments and return objects.
Representation of a class
The declaration of an object is similar to the variable declaration of any basic type. The
necessary space is allocated to an object at this stage. Note that class specification, like a structure,
provides only a template and does not create any memory space for the objects.
78
The object contains data members and member functions. Whenever we create an object for a
class then memory is initialized within the object for its data members and member functions.
Creating Objects:
Syntax: class_name object-1, object-2, . . . . . . . . . . . object-n;
Ex: item x;
Ex: item x, y, z;
[email protected]
member function 2
memory created when
functions defined
memory created
when objects defined
Object of Memory
Example Program:
#include<iostream.h>
#include<conio.h>
class employee
{
int eno;
char ename[10];
float basic;
public:
void getdata( )
{
cout<<”Enter eno, ename, basic = ”;
cin>>eno>>ename>>basic;
}
void disp( )
{
cout<<”\n EmpNum = ”<<eno<<endl;
cout<<\n EmpName = ”<<ename<<endl;
79
cout<<”\n Basic Salary = ”<<basic;
}
};
void main( )
{
clrscr( );
employee e1, e2;
e1.getdata( );
e2.getdata( );
e1.disp( );
e2.disp( );
getch( );
80
Extra Questions:
[email protected]
6. Keywords are not allowed.
7. The length of an identifier can vary (change) from one to several characters.
Ex: sum, a, student, fact, emp, matmult, add_sum.
VARIABLES:
1. A variable is an identifier that is used to represent specified type of data.
2. A variable is a data name, that is used to store the data values or constants at different places
with in a program.
3. A variable is a value; it may change during the program execution.
4. A variable can include the following characters.
Alphabets : a, b, c, …., z and A, B, C, ……,Z.
Numerals : 0, 1, 2, 3, ….., 9
Underscore : ‘_’
5. A variable name starts with an alphabet.
6. The maximum length of variable is 8 characters.
7. A variable does not accept keywords, blank spaces, capital letters, and special symbols except
under score character(_).
Ex: sum, a, student, fact, emp, matmult, add_sum.
[email protected]
1. The names of variables, functions, 1. It is a data name to store the data values
labels and user-defined items are and may change during the program
called as “identifiers”. execution is known as “variable”.
2. All identifiers are not variables. 2. All the variables are Identifiers.
3. Identifiers may not have any memory 3. All variables have a memory.
unless it is a variable.
82
Q: What is a string constant?
Ans: String constant:
1. A string constant is a sequence of characters.
2. Strings must be enclosed in double quotes (“ ”).
3. A character array can hold strings.
4. The characters may be alphabets, numbers, special symbols and blank spaces.
Ex: char s[ ] = “sameeksha”;
char s[ ][ ] = {“sreeram”, “sreetan”};
5. In the above example, string constants are “sameeksha”, “sreeram”, and “sreetan”.
6. Every string constant is terminated be null character (‘\n’).
7. Individual characters can be referred as using indexes.
[email protected]
Q: Explain symbolic constants?
Ans: Symbolic constants:
1. A value of constant with symbolic name in a definition section is called as symbolic constant.
2. Definition section that is “#define” defines all the symbolic constants.
3. A symbolic constant can be defined as,
Syntax: #define symbolic_name value of constant
4. Some valid examples of symbolic constants defined as,
Ex: #define size 10
#define carea 3.14*r*r
#define PI 3.14
5. No blank spaces between “#” and the word “define”.
6. “#” must be the first character.
7. A blank space is required between #define and symbolic name and between symbolic name
and value of constant.
8. #define statement must not end with a semicolon (;).
[email protected]
1. Before processing of the actual program, #include and #define directives are processed first.
2. In the case of #include directives; it specifies the files to be included.
3. In the case of #define directives; it creates a macro that replaces the code of the program
accordingly.
4. The pre-processor statement starts with ‘#’ symbol.
5. Pre-processor statements are not terminated by a semicolon (;).
#include directive:
It is the processed file that has been mentioned in angle brackets. They are, < and >.
For example,
#include<stdio.h>
#include<math.h>
#include<string.h>
#define directive:
It can be placed often at beginning of a program that is before main( ). It creates a macro that
replaces the code of the program accordingly.
84
This is a pre-processor statement; it begins with a “#” symbol. It can be used to define the
symbolic constants. The #define directive searches the macro and replace a constant defined.
Ex: #define PI 3.14
In the above example, where ‘3.14’ is a constant and ‘PI’ is a symbol with constant ‘3.14’.
Whenever ‘PI’ appears in the program it replaced with ‘3.14’.
[email protected]
Q: What is Boolean variable?
Ans: Boolean variable: Boolean variable can be used to hold the integer values 1 or 0. To declare a
Boolean variable in C, use the “bool” macro, which is defined in the header file #include
<stdbool.h>. Here true and false are macros for 1 and 0 respectively.
A Boolean logic test is used to express the results of a logical operation. For example,
bool function(int a, int b)
{
return a = = b;
}
In the above, if a and b have the same value, function( ) returns true. If not, function( ) returns
false.
2. volatile
1. const keyword: Constants are also like normal variables. But only, difference is, their values can’t
be modified by the program once they are defined. They refer to fixed values.
Syntax: const data_type variable_name;
2. volatile keyword: When a variable is defined as volatile, the program may not change value of the
variable explicitly. The value of variable keep on changing without any assignment by the
program, these variables are named as volatile variables.
Syntax: volatile data_type variable_name;
[email protected]
Ans:
CHARACTER VALUE STRING VALUE
2. A character value can take only 2. A string value can take multiple
single character. characters.
86