0% found this document useful (0 votes)
26 views86 pages

C and C++ Notes by Ram

The document discusses the generations of programming languages, categorizing them from low-level (First and Second Generation) to high-level (Third to Fifth Generation) languages. It also covers the processes of compiling, linking, and loading programs, as well as defining algorithms, flowcharts, pseudo-code, and the C programming language's history, advantages, character set, constants, keywords, variables, instructions, data types, and basic structure. Additionally, it highlights the importance of modularity and the characteristics of C as a middle-level programming language.

Uploaded by

rajumahi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views86 pages

C and C++ Notes by Ram

The document discusses the generations of programming languages, categorizing them from low-level (First and Second Generation) to high-level (Third to Fifth Generation) languages. It also covers the processes of compiling, linking, and loading programs, as well as defining algorithms, flowcharts, pseudo-code, and the C programming language's history, advantages, character set, constants, keywords, variables, instructions, data types, and basic structure. Additionally, it highlights the importance of modularity and the characteristics of C as a middle-level programming language.

Uploaded by

rajumahi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 86

Generation and Classification of Programming Languages:

There are five generations of Programming languages. They are:

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

Low Level High Level

First Second Third Fourth Fifth


Generation Generation Generation Generation Generation

Compiling, Linking and Loading a Program:

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.

Analysis of algorithms: Analysis of an algorithm is the process of calculating space required by


that algorithm and time required by that algorithm.

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

Example: Algorithm to add two numbers


Step-1: Read A
Step-2: Read B
Step-3: Let C=A+B
Step-4: Print C

Q: What is a Flow chart? Explain?


A: Flow Chart: To develop an algorithm, we normally draw the Flow charts. Flow chart is a
representation of steps and their order in a graphical manner by using some special symbols.
This diagrammatic representation illustrates a solution model to a given problem. Flowcharts are
used in analyzing, designing, documenting or managing a process or program in various fields.
The two most common types of shapes in a flowchart are:
 A processing step, usually called activity, and denoted as a rectangular box
 a decision, usually denoted as a diamond.

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

A=B False Prints “Not Equal”


?

True

[email protected]
Prints “Equal” stop

Q: What is a Pseudo-code? Explain?


A: Pseudo-code: Pseudo-code is an artificial and informal language that helps the programmers to
develop an algorithm.
 Pseudo-code is similar to English language.
 It does not have any specific syntax (or) rules for representing program.
 They do not directly get executed on computers.
 This code is a general guideline to write the proper syntax.

Pseudo-code is sometimes used as a detailed step in the process of developing a program. It is


possible to write programs that will convert a given pseudo-code language into a given
programming language.
Example:
If student's marks are greater than or equal to 35
Print "passed"
else
Print "failed"

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 :

YEAR LANGUAGE DEVELOPED BY REMARKS

1960 ALGOL - 60 International Too less powerful

[email protected]
Committee

1963 CPL (Combined Cambridge Hard to learn and


Programming Language) University difficult to implement

1967 BCPL (Basic Combined Martin Richards at Could deal with only
Programming language) Cambridge specific problems
University

1970 B Ken Thompson at Could deal with only


AT & T’s Bell specific problems
Laboratories of USA

Dennis Ritchie at Lost generality of B and


1972 C AT & T’s Bell BCPL is restored
Laboratories of USA

Q: Explain the Advantages of ‘C’ language?


4
Ans: Advantages of C language:
C-Programming language is a general programming language because it is very simple,
reliable, easy to use and easy to implement. That’s why C language becomes very popular within a
short time.
C has many advantages. Some of them are,
1). General purpose programming language
2). Powerful programming language
3). Middle level language
4). Portability
5). Modularity

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

Q: List out and explain the C-Character set?


5
Ans: C-Character set:
A C-character set denotes any alphabet, digit, special symbol or blank spaces used to represent
information. Every programming language having its own character set. By using that character set we
can write the programming. The characters in C-language are grouped into following categories. They
are,

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

Q: Define a Constant and explain the constants available in C?


Ans: Constants: A constant is a value that does not change during the program execution. In C-
programming language the constants are divided into two types. They are,
1. Numeric constants
2. Non-numeric constants

Numeric constants Non-numeric constants


6
Integer Real Single Character String Character
constants constants constants constants
Octal Fractional form
Decimal Exponential form
Hexa-decimal
1. Numeric constants: Numeric constants are the Number constants. These are divided into two
types. They are,
a. Integer constants
b. Real constants
a. Integer constants: Integer constant contains a sequence of digits. Integer constant can be
classified into 3 types. They are,

[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’, ‘&’, ‘+’

b. String character constant: It is a sequence of characters or set of characters enclosed in a pair of


double quotation marks (“ ”). These characters may be alphabets or digits or special symbols or blank
spaces.
Ex: “Saanvi”, “Sreetan”, “2164”, “ ”, “abc&$#@”

Q: Define the Keywords of C-language and list them?


Ans: 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 can not be changed.
Keywords can not 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.

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.

The Keywords available in our C-programming language are,


auto double if static
break else int struct
case enum lont int switch
char extern near type def
const float register union
continue far return unsigned
default for short void

[email protected]
do goto signed while

Q: What are the Variables of C-language and Explain?


Ans: Variables: In our C-language, a value it may change during the program execution is called as
variable. A variable is a data name that may be used to store the data value.
A variable may take different values at different times during the program execution. Variable
names may consist of alphabets, digits or underscore character.

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.

Q: What are the Data types in C-programming language?


Ans: Data types: C programming language is rich in its data types. Computer often requires to dealing
with different types of data. This is represented in two different ways. Data types are used to represent
which type of the data actually belongs to. That is basically in 2 categories. They are Primary data
types and Secondary data types.
Primary data types are represented in two types. They are Numeric and Character. Again the
Numeric data can be represented in two types. They are integer and real data types. The computer
can handle these two types of representation in different ways.
In scientific problems, the digits of accuracy are very important. Hence floating point
representation is required. This floating-point representation is expressed in two different forms. They
are fractional form and exponential form. Exponential form is used to represent either too large or
too small number.
In addition to these, non-numeric data is also necessary like characters. This character data
type represents single character or string character.
Hence most of the programming languages provide the data types.
Data types in C: The basic data types of C are int, float, long int, double and char.

9
Memory Conversion
Data type Data Range
size character

int 2 Bytes - 32768 to + 32767 %d

long int 4 Bytes - 2147483648 to + 2147483647 %ld

float 4 Bytes - 3.4 e 38 to + 3.4 e 38 %f

double 8 Bytes - 1.7 e 308 to + 1.7 e 308 %lf

%c (single)
char 1 Byte 0 to 255 (or) - 128 to + 127
%s (string)

Q: Explain the basic Structure of a C-Program?


Ans: Basic structure of a C-Program: A C-program can be viewed as a group of building blocks
called functions. A function that may include one or more statements designed to perform a specific

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

Q: What are the C-Tokens? List them.


A: C Tokens: Basically a Program is a set of statements. The smallest individual units in C- program
are called as Tokens. These tokens are used to build expressions.
C-program contains collection of tokens, comments and white spaces. C-tokens are divided
into five types. They are,
1. Keywords
2. Identifiers
3. Constants
4. Operators
5. Separators

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:

a. Integer constant (Ex: 123)


 Octal integer
 Decimal integer
 Hexadecimal integer
b. Floating point constant (Ex: 12.34)
c. Character constant (Ex: ‘A’)
d. String literals (Ex: “Sam”)

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,

Parenthesis ( ) Used to enclose parameters and also used in expressions


Braces { } Used in functions and control statements
Brackets [ ] Used to declare array type
Semicolon ; Used to separate statements
Comma , Used to separate identifiers
Used to access the data members and member functions of a
Period .

[email protected]
class using object

Q: Explain the Operators available in C-language?


Ans: C – Operators: An operator is a special symbol that tells to the computer to perform certain
mathematical or logical manipulations (operations). Operators are used to manipulate the data and
variables.

C-operators can be classified in to number of categories. They are,


1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operator
5. Increment and Decrement operators
6. Conditional operator
7. Bitwise operators
8. Special operators

1. Arithmetic operators: C-programming language provides all the basic arithmetic operators.
They are,
Operator Meaning
+ Addition or Unary Plus

- Subtraction or Unary Minus


* Multiplication
/ Division
% Modulo Division

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,

Operator Meaning Example Result


< Less than 3<4 True
> Greater than 3>4 False
<= Less than or Equal to 3<=4 True
>= Greater than or Equal to 3>=4 False
== Equal to 3==4 False

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

Operator Meaning Example Result


&& Logical AND 4 > 2 && 4 < 2 False
|| Logical OR 4 > 2 || 4 < 2 True
! Logical NOT 4==2 True

&& is True when all conditions are True.


|| is True when one of the conditions is True.
! is True when the condition is False.

4. Assignment operator: Assignment operator is used to assign the result of an expression to a


variable. The usual assignment operator is “=”.
Syntax: Variable = expression;
Ex: c = a + b;
5. Increment and Decrement operators: C-language has two very useful operators. These operators
are not found in other languages. The increment and decrement operators are “++” and “- -“.
Ex: a ++;
a - -;
Here, a ++ is equivalent to a=a+1
a - - is equivalent to a=a-1

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;

In the above expression it evaluates true-statement or false-statement is depending on the


condition. If the condition is true, then the true-statement is executed otherwise false-statement is
executed.

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

Q: Write about precedence of Arithmetic operators?


A: Precedence of Arithmetic Operators: An Arithmetic expression without any parenthesis will be
evaluated from left to right using the rules of precedence of operators. There are two priority levels
of arithmetic operators in C. They are,
High level priority operators: *, /, %
Low level priority operators: +, -

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)

The order of evaluation can be changed by introducing parenthesis into an expression.


Whenever the parenthesis is used, the expressions within parenthesis assume highest priority. If

[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: double is large enough to hold int value. Therefore,


18
int m=50;
double n=m; // Implicit casting

This is also called “Widening conversion”.

We can mix data types in expressions. For example, a=5+2.75;


That is a valid statement. Wherever data types are mixed in an expression, C++ performs the
conversions automatically. This is process is known as Implicit or Automatic conversion.

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.

For Ex: float a=2.5;


int b=a; // raises compilation error
int b=int(a); // Explicit casting and 0.5 is truncated

This is called “Narrowing conversion”.

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

Q: What are Input and Output statements of C-language? Explain?


19
Ans: Input statements: What we are giving to the computer is known as Input. The statements that
are used to give an input to the computer are known as Input statements.
Output statements: What we are taking from the computer is known as Output. The statements that
are used to take an output from the computer are known as Output statements.
In our C-language, the input and output statements can be classified mainly into two types.
They are,
1. Formatted Input and Output statements.
2. Un-formatted Input and Output statements.

1. Formatted Input and Output statements:


The input and output statements, which are performed by using format specifiers (conversion
characters (%d, %ld, %f, %lf, %c, %s)) known as “Formatted input and output statements”.

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

b) printf( ): It prints the formatted text on the screen. It is an output 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.

2. Un-formatted Input and Output statements:


The input and output statements, which are performed without format specifiers (conversion
characters) known as “Un-formatted input and output statements”.
In our C-language, the various Un-formatted input and output statements are,

a) getchar( ): It is an input statement. It reads a character from a keyboard.

b) putchar( ): It is an output statement. It prints a character ont the screen.

c) gets( ): It is an input statement. It reads a string from a keyboard.

d) puts( ): It is an output statement. It prints a string on the screen.

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;

Flow chart: Start

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

Flow chart: Start

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

False False True True


Cond- Cond- Cond-
3? 1? 2?

True False

Statement Statement Statement Statement


Block-4 Block-3 Block-2 Block-1

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

Default Statement Block Statement-x

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.

2. Multi-way Conditional control statement: In Multi-way conditional control statement, it is


implemented by using the keyword switch.
The switch statement is used to select any one statement block from a possible of several
alternatives. That’s why; this statement is also called as “Multi-way conditional control statement”.
The selection will be based on the correct value of an expression. The expression in switch statement
must be an integer constant or single character constant type.

Syntax: switch (expression)

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

Ex: Sum of given 10 positive values


main( )
{
int i, n, sum=0;
clrscr( )
i=1;
while ( i<=10 )
{
printf(“enter any value = ”);
scanf(“%d”, &n);
if(n<0)
{
continue;

[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

True False Statement-x


Cond
?
In the above, the body of loop gets executed first, and then the test-condition is evaluated. If the test-
condition is true, the body of loop is executed once again. This process of repeated execution continues until the

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

Syntax: for (Initialization; Test-condition; Increment / Decrement)


{
Body of loop;
}
statement-x;

Flow chart:

Start

Initialization

False
Cond Statement-x
?
True

Statement block

Increment / Decrement

i. Initialization of the control variable is done first.


ii. Next the test-condition is evaluated. If the condition is true, the body of loop is executed,
otherwise the loop is terminated.
30
iii. When the body of loop is executed, the control is transferred to the increment / decrement section.
iv. After increment / decrement, again the test-condition is evaluated. If the condition is true, the body
of loop is again executed.
v. This process continues until the condition is being is true. If the condition becomes false, then the
control is transferred to the statement-x and the loop will be stop.

Q: Differentiate while and do while loop control statements?


Ans:

while loop do while loop

1. It is top testing loop. 1. It is bottom testing loop.

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.

4. Minimum number of executions in the 4. Minimum number of executions in the


while loop are “zero”. do-while are “one”.

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

1. System-defined functions: System-defined functions are called as “Library functions” or “Built-in


functions”. They are defined by C-compiler and are included in Header files.
Ex: sqrt (x);
pow (x, n);

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

Q: Explain different ways of writing functions in C-language?


Ans: A function that depends on the arguments are present or not and whether a value is returned or
not. The different ways of writing functions can be classified into four types. They are,

1. With arguments and with return value.


2. With arguments but no return value.
3. No arguments but returns a value.
4. No arguments and no return value.

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

main( ) function-1 ( datatype var_name)


{ {
------ value of args ------
------ ------
function-1 (a) ; function return (n) ;
------ returning value }
------
}

Two way data communication between functions


34
The nature of data communication between calling function and called function is with
arguments and returns value.
main( )
{
------
------
function-1 (a1, a2, . . . . . , an); /*calling function*/
------
- - - - - - Actual arguments
}
return data type functioin-1 (data type x1, data type x2, .., data type xn) /*called function*/
{
------ Formal arguments

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

One-way communication between the functions


The nature of data communication between calling function and called function is with
arguments but no return value.
main( )

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

Ex: void fact (int);


main( )
{
int n;
clrscr ( );
printf (“Enter any number = ”);
scanf (“%d”,&n);
fact (n);
getch( );
}
void fact (int n)
{
int i, f;
for (i=1, f=1; i<=n; i++)
{
f=f*i;
}
printf (“Factorial of a given number = %d”, f );
}
36
3. With no arguments but returns a value: A function that does not take any arguments but
returns a value is known as a “Function with no arguments but returns value”.

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

In C-language, there are 2 types of parameter passing techniques. They are,

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.

Ex: void swap(int *, int *);


main( )
{
int a =10, b = 20;
clrscr( );

[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

Finally the called function returns “f” to the calling function.

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.

Ex: int a [10];


In the above, One-dimensional array represents either “one row with number of columns” or
“one column with number of rows”.
In the above example, ‘a’ is an array name and 10 is the maximum size of an array. It can hold
maximum of 10 integer values. And “int” is its data type. Array ‘a’ occupies 20 bytes of memory,
because each integer value occupies the 2 bytes of memory.

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

Declaration of One-Dimensional Array:


The syntax of One-dimensional array declaration is,
Syntax: Datatype array_variable_name [maximum_size];

In the above syntax,


 The data type specifies the data types 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.

Ex: int a [10];


In the above example, ‘a’ is an array name and 10 is the maximum size of an array. It can hold
maximum of 10 integer values. And “int” is its data type. Array ‘a’ occupies 20 bytes of memory,
because each integer value occupies the 2 bytes of memory.
Array indexing starts from ‘0’ and ends with one less than the size that is ‘9’.

Initialization of One-Dimensional Array:


The syntax of initialization of One-dimensional array is,

Syntax: Datatype variable_name [maximum_size] = { list of values };


Array initialization can be done as,
int a[3] = {10, 20, 30};
This is similar to the following statements,
a[0] = 10;
43
a[1] = 20;
a[2] = 30;
If an array is initiated in the declaration itself, then it is not necessary to give the size of an
array.
int a[ ] = {10, 20, 30};
This is similar to
int a[3] = {10, 20, 30};

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.

Declaration of two-dimensional array:


The syntax of two-dimensional array is,
Syntax: Datatype array_variable_name [row_size] [column_size];

In the above syntax,


 The data type specifies the data types of the elements such as int, float or char.
 The variable_name specifies the array name.
 The row_size indicates the maximum number of rows, and column_size indicates the
maximum number of columns.
That is array holds the total number of elements are “row size x column size”.

Ex: int a [2] [3];


In the above declaration defines “six” indexed variables with an array ‘a’. The six indexed
variables are as follows,
a [0] [0], a [0] [1], a [0] [2]
a [1] [0], a [1] [1], a [1] [2]

Initialization of Two-dimensional array:


In two-dimensional arrays the initialization is same as one-dimensional array. That is,
Ex: int a[ ] [ ] = { {10, 20, 30}, {20, 30, 40} };

This is similar to the following statements,


44
a [0] [0] = 10;
a [0] [1] = 20;
a [0] [2] = 30;
a [1] [0] = 20;
a [1] [1] = 30;
a [1] [2] = 40;

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.

Similarly, if it is an array with 4-subscripts, then it is called as Four-dimensional array.


The syntax of Multi-dimensional array is,
Syntax: Datatype array_variable_name [size-1] [size-2] [size-3] . . . [size-n];

[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”.

Q: What is Sorting? Explain with example?


Ans: Sorting: Sorting is a technique used to arrange the elements of an array in the order, that is either
in ascending or descending order. To implement this sorting technique there are several logics, such as
Selection sort, Bubble sort, Quick sort and etc.
Ex: main( )
{
int a[5] = {2, 4, 3, 1, 5}, i, j, t;
clrscr ( );
printf(“\nBefore Sorting = “);
for(i=0; i<5; i++)
{
printf(“%4d”, a[i] );
}
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;
}
}
}
47
printf(“\nAfter Sorting = “);

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


{
printf(“%4d”,a[i] );
}
getch( );
}
In the above example, after sorting it prints the elements of an array in ascending order. That
is, the elements must be 1 2 3 4 5.

Q: What is Merging? Explain with example?


Ans: Merging: Merging is a technique used to merge the elements of two arrays into the third array.
That is,

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

Ex: void disp(int [][], int, int);


main()
{
int a[2][2] = {{1, 2}, {3, 4}};
clrscr();
disp(a, 2, 2);
getch();
}
void disp(int a[2][2], int m, int n)
{
int i, j;
for( i=0; i<m; i++ )
{
for( i=0; i<n; i++ )
{
printf(“%4d”, a[i][j]);
}
printf(“\n”);
}
}
In the above example, two-dimensional array ‘a’ is send to the function disp( ) as an argument,
then the disp( ) prints all the values of the given matrix ‘a’.

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,

Syntax: Datatype String_variable_name[maximum_size];


Example: char s[10];

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

To print the string we may write,


printf (“%s”, s);

To print the individual characters of a string, then we may write,


for ( i=0; i<7; i++ )
{
printf(“%c”, s[i]);
}

It is possible to write or initialize the set of strings as follows,


char s[10][10] = { “sreetan”, “sameeksha”, “sreeram” };
In the above expression, the first ‘10’ size indicates the maximum number of strings and
second ‘10’ size indicates the maximum number of characters in each string.
for ( i=0; i<3; i++ )
{
printf(“%s\n”, s[i]);
}

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”

c). strrev( ): It is used to reverse a string.


Syntax: strrev(string_variable);
Ex: strrev(s);

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

s1 s2 string function return value


“abc” “abc” strcmp(s1, s2) 0
“abc” “aac” 1
“madam” “madam” 0
“abc” “bbc” -1

e). strcat( ): It is used combine the two strings.


Syntax: strcat(string1, string2);
Ex: strcat(s1, s2);
In the above example, s2 can be combined to the s1.
s1 s2 string function s1 s2
“sree” “ram” strcat(s1, s2) “sreeram” “ram”
“abhi” “ram” “abhiram” “ram”
“raghu” “ram” “raghuram” “ram”
53
f). strlwr( ): It is used to convert the given string into lowercase.
Syntax: strlwr(string_variable);
Ex: strlwr(s);
Before execution of s string function After execution of s
“SREERAM” strlwr(s) “sreeram”
“ABHIRAM” “abhiram”
“Raghuram” “raghuram”

g). strupr( ): It is used to convert the given string into uppercase.


Syntax: strupr(string_variable);
Ex: strupr(s);

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

Syntax: Datatype * pointer_variable_name;


Ex: int *a;

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

int a=10, *b;

clrscr( );

b=&a;

printf(“%d\n”, a); /*accessing the value by name*/

printf(“%d\n”, *(&a)); /*accessing the value by pointing to the address*/

printf(“%d\n”, *b); /*accessing the value by pointing to the pointer variable*/

getch( );

55
Memory Organization

Memory Cells Address


0
1
2

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

Q: what is an importance of Pointers in C and explain the pointer arithmetic?


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,
Syntax: Datatype *pointer_variable_name;
Ex: int *a;

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

Q: What are * and & operators? Explain their utility.

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

We can also use the operators such as +, -, ++, - - on addresses.


int a[ ] = {10, 20, 30};
57
printf(“%d”, *(&a[0]) ); /* prints 10 */
printf(“%d”, *(&a[0]+1) ); /* prints 20 */

Q: Explain about Dynamic Memory Allocation with example.


A: Dynamic Memory Allocation: Allocating the memory at the time of running a program is known
as Dynamic Memory Allocation.
 It eliminates predetermining of number of variables to be used in the program.
 This mechanism is purposefully used in data structures like linked lists and binary trees.
 In dynamic memory allocation our purpose is served, we can release the memory to avoid
blocking the memory.
C provides some functions to achieve these tasks. There are, 4 library functions provided by C
defined under <stdlib.h> header file to provide dynamic memory allocation in C programming.

[email protected]
They are,
1. malloc( )
2. calloc( )
3. free( )
4. realloc( )

1. malloc( ): ‘malloc( )’ or ‘memory allocation’ method is used to dynamically allocate a single


large block of memory with the specified size.

Syntax: ptr = (cast-type *) malloc (byte-size);


Example: ptr = (int *) malloc sizeof(int);

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

4 realloc( ): ‘realloc( )’ or ‘re-allocation’ method is used to dynamically change the memory


allocation of a previously allocated memory.de-allocate the memory. In other words, if the
memory previously allocated with the help of malloc or calloc is insufficient, realloc can be
used to dynamically re-allocate memory.
Syntax: ptr = realloc(ptr, newSize);

Q: what is a structure? Explain with example?


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,
struct structure_name
{
datatype member-1;
datatype member-2;

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

7. Here (.) is called as member selection operator.


8. The memory size of the structure variable is equals to the sum of sizes of all the members in a
structure.

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

Structure within a structure (Nesting of structure):


Structure within a structure is called as nesting of structures.
Ex: main( )
{
struct student
{
int rno;
char name[10];
struct marks
{
int m1;
int m2;
}m;
}s;
clrscr( );
printf(“enter rno, name, m1, m2 = ”);
scanf(“%d %s %d %d”, &s.rno, &s.name, &s.m.m1, &s.m.m2);
printf(“RNo=%d \n Name=%s \n”, s.rno, s.name);
printf(“M1=%d \n M2=%d”, s.m.m1, s.m.m2);
getch( );
}

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.

Q: Explain Union in C with example?


Ans: UNION: Union 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.
Union is a concept borrowed from structures. The union syntax is same as structure syntax. In
structures, each member is having its own memory location. But in unions, all the members can use
the same memory location. That is, in unions only one member can handle at a time.
The syntax of union is,
Syntax:
union union_name

[email protected]
{
datatype member-1;
datatype member-2;

datatype member-n;
};
union union_name variable_name;

Ex: union sample


{
int a;
float b;
char c;
};
union sample s;

The union sample variable ‘s’ size is 4 bytes. Because the maximum size of the member is ‘b’
has 4 bytes.

Storage location of 4 bytes

c = 1 byte
c a = 2 bytes
a b = 4 bytes
b

Sharing of storage location by union members

61
Q: Compare structures and unions with syntax and examples?
Ans:
STRUCTURES UNIONS

1. Using structures we can define 1.Using unions we can define


user-defined data types. user-defined data types.

2. Using structures we can hold 2.Using unions we can hold a


set of different data values. single value.

3. The structure declaration starts 3. The union declaration starts


with a keyword “struct”. with a keyword “union”.

4. Members of the structure 4. Members of the union variables

[email protected]
variables are accessed with are accessed with ( .) operator.
(.) operator.

5. Members of the structure 5. Members of the union share


contain individual memory common memory location.
location.

6. Structure variable size equals 6. Union variable size is the


to the sum of sizes of all the highest memory size of the
members. member in the union.

7. Syntax: 7. Syntax:
struct structure_name union union_name
{ {
datatype member-1; datatype member-1;
datatype member-2; datatype member-2;

datatype member-n; datatype member-n;


}; };
st ru ct st ru ct ure_n am e vari abl e_n am e; u ni on un i on _n am e vari abl e_n am e;

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

Q: Explain about Enumeration data type with example?


Ans: Enumeration data type:
Enumeration is a secondary data type and it is also called as user-defined data type. This data

[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”.

Syntax: enum enumeration_name


{
member-1,
member-2,

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.

[email protected]

Function Function

Data

Function Function

Object = Data+ Functions

Object A Object B

Data Data

Communication
Functions Functions

Object C

Functions

Data

Organization of Data and Functions in OOP


65
The Data of an Object can be accessed only by the functions associated with that object.
However, functions of one object can access the functions of other objects.

Q: Explain the structure of C++ program?


A: Structure of a C++ program:

Include files

Class declaration

Member functions definitions

Main function program

Structure of a C++ program

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

These member functions can be defined in two places:


 Outside the class defniton
 Inside the class defniton
 Maio fuoctio prigram: Every C++ applicaton program should contain the main( ) functon. And every C+
+ program executon should starts from this main( ) functon. This main( ) functon is the essental part of
the C++ program.
A simple C++ program can contain only this main( ) function part.
Q: Explain about the basic Input and Output statements of C++?
A: Input statement: The statement which is used to give an input to the computer is known as Input
statement. The statement
cin >> a;

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.

Object Extraction operator Variable


cin >> 45.5

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

cout << “Welcome to C++”;

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

cout << 45.5


Object Insertion operator Variable
Output using Insertion Operator

Q: What are the Storage classes? Explain with examples?


A: STORAGE CLASSES: Storage classes are used to explain the behavior of variables. Behavior of
variable includes Storage location, Default initial value, Scope and Life.

Storage class of a variable determines,


a) Where the variable would be stored (that is, Storage location).

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,

1. Automatic storage class


2. Register storage class
3. Static storage class
4. External storage class

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

Storage location : Memory


Default initial value : Some Garbage value (if the value is not assigned)
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

Example for Automatic storage class variable:


void sample( )
{
auto int a=0;
cout<< a;
a++;
}
Output: 0 0 0
In the above example, when the variable ‘a’ is auto, then each time sample( ) is called and it is
reinitialized to ‘0’. When the function terminates, then ‘a’ vanished and its new value of ‘1’ is
lost. That is why, ‘a’ is initialized to ‘0’ and every time and prints ‘0’.

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.

Ex: void sample( )


{
register int a=0;
cout<< a;
a++;
}

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

Storage location : Memory


Default initial value : Zero
Scope : Local to the block, that is in which the variable is defined
Life : Value of the variable keep on doing between different
function calls
Example: void sample( )
{
auto int a=0;
cout<< a;
a++;
}
Output: 0 0 0

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)

Example for External storage class variable:


#include<iostream.h>
#include<conio.h>
void increment( );
int a;
void main( )
{
clrscr( );
cout<< a<<”\t”;
increment( );
increment( );
a++;
cout<<a<<”\t”;
getch( );
}
void increment( )
{
a++;
cout<<a<<”\t”;
}
Output: 0 1 2 3

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

Q: Compare Local and Global variables with examples?


A:
Local Variables Global Variables
Local variables are “Automatic storage class” Global variables are “External storage class”
type variables. type variables.
Local variable does not take any initial value. Global variable automatically gets initialized
It takes the garbage value. to ‘0’ (zero).

[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

Q: What are the similarities and differences between C and C++?


72
A: The Similarities between C and C++ are:
 Both C and C++ are static languages.
 Both C and C++ uses #include for including header files.
 Both C and C++ executes top to bottom.
 Both C and C++ allows procedural programming.
 Both C and C++ allows functional programming.
 Both C and C++ uses ‘;’ as statement terminator.
 Both C and C++ supports multidimensional arrays.
 Both C and C++ does not support dynamic sized arrays.
 Both C and C++ can run on any platform provided it has a compiler.

The Differences between C and C++ are:

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

Q: Describe the basic concepts of Object-Oriented programming?


73
A: The basic concepts of Object-Oriented Programming which form the heart of C++ programming
language. They are,

1. Objects
2. Classes
3. Data Encapsulation
4. Data Abstraction
5. Information Hiding
6. Inheritance
7. Polymorphism
8. Dynamic binding
9. Message communication

1. Objects: Objects are the basic runtime entities in an object-oriented system.

[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

2. Classes: A class is a user-defined data type and an object is a variable of that


data type. Once a class has been defined, we can create any number of objects belonging to
that class. Each object is associated with the data of class data type in which they are created.
A class is a collection of objects of similar type. For example, the syntax used to create an
object is,

If ‘fruit’ has been defined as a class, then the statement is,


fruit mango;
In the above statement will create an object ‘mango’ belonging to the class ‘fruit’. 74
3. Data Encapsulation: Encapsulation means combining. Data Encapsulation is a mechanism of
combining the data and functions into a single unit.
Data Encapsulation is the most striking feature of a class. The data can access by the
functions but not accessible to the outside. These functions provide an interface between the
object’s data and the program.

Data
Information “in” and Information “out”
Functions

4. Data Abstraction: A mechanism that is creating new data types using


encapsulated items is known as “Data Abstraction”.

[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 class Parent Base or Super class


features

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.

9. Message communication: An object-oriented programming consists of a set of


objects that communicate with each other.
Message communication is the concept of message passing, makes it easier to
communicate between objects when a program is executed, then the objects interact with each other by
sending messages, but without knowing the details of each other’s data (or) code.

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

The general form of a class declaration is:

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

Entry allowed to public area Data

Functions

Data hiding in classes


A Simple Class Example:
class item
{
int number; // variable declarations
float cost; // private by default
public:
void getdata (int a, float b); // function declarations using prototype
void putdata ( );
};
77
We usually give a class some meaningful name, such as item. This name now becomes a new type
identifier that can be used to declare instances of that class type. The class item contains two data
members and two member functions. The data members are private by default and both the member
functions are public by declaration.
The function getdata( ) can be used to assign values to the data members number and cost, and
putdata( ) for displaying their values. These functions provide the only access to the data members
from outside the class. It means that the data cannot be accessed by any function that is not a member
of the class item. Note that the functions are declared, not defined.
Properties of a Class:
1. Class has both data members and member functions.
2. A member may be either public (or) private.
3. The members of a class are private by default.

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

Q: What is an Object? Explain the creation of an object with example.


A: Objects: The declaration of class does not define any objects but only specifies what they will
contain. Once a class has been declared, we can create variables of that type by using the class
name. In C++, the class variables are known as objects. The Object is an instance of a class.

Class : ITEM DATA


DATA
number getdata( )
cost
putdata( )
FUNCTIONS
getdata( )
putdata( )

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;

Memory Allocation for Objects:

Common for all Objects


member function 1

[email protected]
member function 2
memory created when
functions defined

Object 1 Object 2 Object 3


member variable 1 member variable 1 member variable 1

member variable 2 member variable 2 member variable 2

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

[email protected]

80
Extra Questions:

Q: Explain, what are the identifiers and variables?


Ans: IDENTIFIERS:
1. The names of variables, functions, labels and user-defined items are called as Identifiers.
2. An identifier can include the following characters.
Alphabets : a, b, c, …., z and A, B, C, ……,Z.
Numerals : 0, 1, 2, 3, ….., 9
Underscore : ‘_’
3. An identifier starts with an alphabet.
4. Special symbols are not allowed except underscore character (_).
5. It can not include blank spaces.

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

Q: Explain typedef with example?


Ans: “typedef” is a keyword. “typedef” is used for designing aliases for data types. That is, user can
give another name for data tupes to be used in the program.
Ex: main( )
{
typedef int sam;
typedef int ram;
81
sam a=10;
ram b=20;
clrscr( );
printf(“Addition of a, b values = %d”, a+b);
getch( );
}
In the above program, writing “sam” is as defined as writing “int” and writing “ram” is as
defined as writing “int”.
Hence, “sam” and “ram” are defined as “int”. Hence, ‘a’ and ‘b’ are treated as of type “int”.

Q: Compare identifiers and variables with examples?


Ans:
IDENTIFIERS VARIABLES

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

4. Mentioning the type of an identifier 4. The type of a variable must be defined.


is not needed unless it is a variable. Ex: sum, a, s_i, a1
Ex: sum, a, student, fact, s_i

Q: What is Boolean expression?


Ans: Boolean expression: An expression which gives either true or false is called as “Boolean
expression”. That is, this is a result of an application of relational operator.
<, >, <=, >=, ==, !=
In our C-language, integer values can also be Boolean expression. Because a non-zero value is
treated as true and a zero value is treated as false.
Example:
int a=5;
if(a>0)
{
printf(“positive”);
}
In the above example, a>0 is a condition and it returns the true as a Boolean expression.

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

Q: Define Built-in functions in C?


Ans: Built-in functions: The functions which are already defined in ‘C’ known as “Built-in
functions”. These are also called as pre-defined functions. These are provided by ‘C’ itself. We need
not define the Built-in functions, because these are pre-defined. That is, we need not provide any code
for the built-in functions.
These functions can be performed using header files. It depends upon including the header files
we can use those functions.
For example: The header file #include<math.h> performs mathematical functions such as sqrt( ),
pow( ), sin( ), cos( ), tan( ) and etc.
83
Q: What are Pre-processor statements? Explain? (OR)

Explain #define and #include directives? (OR)

What are compiler directives? Explain?


Ans: Pre-processor statements:
The pre-processor mechanism allows different directives such as, #include and #define.
#include directives can be declared in the link section and #define directives can be declared in the
definition section in the program.
Link section is used to link some functions in the program such as, input and output functions,
mathematical functions, string functions and character type functions to the C-system library using the
compiler.
Definition section defines all the symbolic constants.

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

Where, “stdio.h” means, it performs input and output functions.


Ex: scanf( ), printf( )

“math.h” means, it performs mathematical functions.


Ex: sqrt( ), pow( )

“string.h” means, it performs string functions.


Ex: strlen( ), strcpy( ), strrev( ), strcmp( )

#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’.

Q: What is Top-down programming?


Ans: Top-down programming: Top-down programming is the opposite of Bottom-up programming.
Top-down programming refers to a style of programming where an application is constructed
starting with a high-level description of what it is supposed to do, and breaking the specification down
into simpler and simpler pieces, until a level has been reached. Top-down programming method
results in some forms of stepwise refinement.

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

Q: What are C-Tokens?


Ans: C-Tokens: C tokens are the basic building blocks in C language which are constructed together
to write a C-program.

The different types of C-tokens are,


1. Keywords (Ex: int, float, while, for)
2. Identifiers (Ex: a, b, total, fact( ))
3. Literals or Constants (Ex: 10, 2.5, “sam”)
4. Operators (Ex: +, /, *)
5. Separators (Ex: ( ), { })

Q: What about Type Qualifiers?


Ans: Type Qualifiers: The keywords which are used to modify the properties of a variable are called
Type Qualifiers.
There are 2 types of Qualifiers available in C language. They are,
85
1. const

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;

Q: What is the difference between character value and string value in C?

[email protected]
Ans:
CHARACTER VALUE STRING VALUE

1. It belongs to standard or primary 1. It belongs to primary data type


data type. (or) it may be belongs to
secondary (or) structured data
type.

2. A character value can take only 2. A string value can take multiple
single character. characters.

3. While assigning a character 3. While assigning a string value


value, the value must be enclosed the value must be enclosed in
in “single quotes”. “double quotes”.

4. A single character value can be 4. A string value can be assigned


assigned in a single character in array character type variable
type variable name as, name as,
char ch = ‘a’; char s[] = “sreetan”;

5. The conversion characters used 5. The conversion characters used


for printing a character value is “%c”. for printing a string value is “%s”
.

86

You might also like