0% found this document useful (0 votes)
2 views103 pages

cNew

The document provides a comprehensive overview of computer hardware and software, detailing their components and functions. It explains the process of creating and running programs, including writing, compiling, linking, and executing. Additionally, it covers program development cycles, algorithms, flowcharts, and their advantages and disadvantages.
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)
2 views103 pages

cNew

The document provides a comprehensive overview of computer hardware and software, detailing their components and functions. It explains the process of creating and running programs, including writing, compiling, linking, and executing. Additionally, it covers program development cycles, algorithms, flowcharts, and their advantages and disadvantages.
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/ 103

1. List and explain the functions of various parts of computer hardware and software.

Ans : Computer System :


A computer is a system made up of two major components:

I. Computer Hardware.

II. Computer Software.

The following figure shows a computer system.

Fig : A Computer System


I. Computer Hardware:
The computer hardware is the physical equipment. The hardware component of
computer system consists of 5 parts
A. Input Devices.
B. Central Processing Unit ( CPU ).
C. Primary Storage.
D. Output Devices.
E. Auxiliary Storage Devices.
The following figure shows the hardware components.

Fig: Hardware Components


A. Input Devices: The input device is usually a keyboard where programs and data are
entered in to the computer. Other Input Devices : a touch screen , a mouse , a pen , an audio
input unit.

B. Central Processing Unit ( CPU ): It is responsible for executing instructions such as


arithmetic calculations , comparisons among data and movement of data inside the system. Today’s
computers may have one or more CPU’s

C. Primary Storage: It is also known as main memory . It is a place where the programs and
data is stored temporarily during processing. The Data in primary storage is erased
, when we turn off a personal computer or when we log off from a time-sharing
computer ( volatile ).

D. Output Devices: The output device is usually a monitor or a printer to show


output. If the output is shown on the monitor, it is a soft copy and if the output is printed on
the printer, it is a hard copy.

E. Auxiliary Storage Devices ( secondary storage devices ): It is used for both input and output.
It is also known as secondary storage. It is a place where the programs and data are
stored permanently. when we turn off the computer the programs and data remain in the
secondary storage, ready for the next time when we need them.

II. Computer Software : Software is the collection of Programs ( instructions ) that allow
the hardware to do its job.
They are two types of Computer Software.
A. System Software
B. Application Software

The following figure shows the Computer Software.

Fig: Computer Software


A. System Software:
System Software consists of programs that manage the hardware resources
of a computer and perform required information processing tasks.

These programs are divided in to three classes.

i. Operating System Software.


ii. System Support Software.
iii. System Development Software.

i. Operating System Software: It provides services such as a user interface, files and data base
access and interfaces to communication systems such as Internet protocols. The primary
purpose of this software is to keep the system operating in an efficient manner while
allowing the users access to the system.
ii. System Support Software : System Support Software provides system utilities and other
operating services. Examples of system utilities are sort programs and disk format programs.
Operating services consist of programs that provide performance statistics for the operational
staff and security monitors to protect the system and data.
iii. System Development Software: It includes language translators that convert programs in to
machine language for execution , debugging tools to ensure that programs are error - free and
computer -assisted software engineering ( CASE ) systems.

B. Application Software: It is directly responsible for helping users to solve their problems.
Application software is broken in to two classes.
i. General - Purpose Software
ii. Application - Specific Software
i. General Purpose Software: It is purchased from a software developer and can be used for
more than one application. Examples: word processors, database management systems, computer –
aided design systems. They are labeled general purpose because they can solve a variety of user
computing problems.
ii. Application Specific Software: It can be used only for its intended purpose.
Example: A general ledger system used by accountants.
They can be used only for the task for which they were designed.They can not be used for
other generalized tasks.
Relationship between system and application software is shown in the figure:

Fig: Relationship between System and Application Software


Each circle is an interface point. The inner core is hardware. The user is represented by
the outer layer. To work with the system , the typical user uses some form of application
software. The application software in turn interacts with operating system ( OS ), which is part of
system software layer. The System software provides the direct interaction with the hardware.
The opening at the bottom of the figure is the path followed by the user who
interacts directly with the Operating System when necessary.

2. Explain Creation and Running of Programs ?


or
Describe how the Developers will Write the Programs ?

Ans: CREATING AND RUNNING PROGRAMS :


It is the job of programmer to write and test the program.The following are four steps
for creating and running programs:
A. Writing and Editing the Program.
B. Compiling the Program.
C. Linking the Program with the required library modules.
D. Executing the Program.

A. Writing and Editing Program : The Software to write programs is known as text
editor. A text editor helps us enter , change and store character data. Depending on the
editor on our system, it could be used to write letters, create reports or write programs.
Example : word processor.
The text editor could be generalized word processor, but every compiler comes with
associated text editor. Some of the features of editors are
Search : To locate and replace statements.
Copy , Paste : To copy and move statements.
Format : To set tabs to align text.
After the program is completed the program is saved in a file to disk. This file will be
input to the compiler, it is known as source file. The following figure shows the various
steps in building a C – program.

Fig: Building a C - program

B. Compiling Programs: The code in a source file on the disk must be translated in to
machine language. This is the job of compiler which translates code in source file stored on
disk in to machine language. The C compiler is actually two separate programs: the
preprocessor and the translator. The preprocessor reads the source code and prepares it for
the compiler. It scans special instructions known as preprocessor commands. These commands
tell the preprocessor to take for special code libraries, make substitutions in the code. The
result of preprocessing is called translation unit. The translator reads the translation unit
and writes resulting object module to a file that can be combined with other precompiled
units to form the final program. An
object module is the code in machine language. This module is not ready for execution
because it does not have the required C and other functions included.

C. Linking Programs: C programs are made up of many functions.


Example: printf ( ) , cos ( )… etc
Their codes exists else where , they must be attached to our program. The linker
assembles all these functions , ours and the systems, in to a final executable program.
D. Executing Programs : Once our program has been linked, it is ready for execution.
To execute a program, we use operating system command, such as run to load the
program in to main memory and execute it. Getting program in to memory is the
function of an Operating System programs called loader. Loader locates the executable
program and reads it in to memory. In a typical program execution,
the program reads data for processing, either from user or from file. After the program
processes the data, it prepares output. Data output can be to user’s monitor or to a
file. When program has executed, Operating System removes the program from memory.

3. List and Explain about the Program Development?


or
Explain how the Developers will Test the Program?
or
What do you mean by ‘program development cycle’? Explain the steps involved in it?
0r
What are different steps followed in program development ?

Ans: Program Development :


Program Development is a multi step process as follows
A. Understand the Problem
B. Develop a Solution - Algorithm - Pseudo code - Flowchart
C. Write a Program
D. Test it.
For program development , developers are given
Program requirement statement
Design of program interfaces
Overview of the complete project

A. Understand the problem :The first step in solving any problem is understand it. We
begin by reading the requirements statements carefully.When we think that we fully understand
it, we review our understanding with the user and the system analyst.
Example: Calculate the square footage of house.
The questions that arise are
1. What is definition of square footage ?
2. How is it useful ?

B. System requirement: We do planning of functional requirements - Software’s


Version, Non-functional requirements - Resources - Internet , table , A/cs , Coffee. User
functional requirements - Problem Oriented and Language used is in simple i.e. English.

C. Analysis: User requirements are transformed to technical terms like Blueprint and
also look for different alternatives considering all risks.

D. Design: In UML software users will develop flowcharts, structure charts, data flow diagrams
1. Choose the best way to find solution among different alternatives.
2. Choose in analysis , design files , databases and functions.
E. Code:
Unimportant in Software development life cycle
1. Uses software for code generation ( forward energy ).
2. Otherwise go for manual coding.
3. Basic testing is done ( compilation ).

F. System Test :Test if user requirements are met Blackbox Testing: Test programs
together, make sure system works as a whole. Whitebox Testing: Release ά-version to
customer, according to his/her feed back we develop β-Version: β - version is released to
selected group of people.
G. Maintenance :
Keeps the system working once it has been put in to production ?

4. Explain about Algorithm ?


or
Define Algorithm and State Properties of it ?
Ans: Algorithm :
Algorithm is a finite set of instructions that , if followed accomplishes a particular task.
Algorithm should satisfy the following criteria
1. Input : Zero or more quantities are externally supplied.
2. Output : At least one quantity is produced.
3. Definiteness : Each instruction is clear and unambiguous. Ex Add B or C to A
4. Finiteness : Algorithm should terminate after finite number of steps
when traced in all cases
Ex: Go on adding elements to an array
5. Effectivenes: Every instruction must be basic i.e., it can be carried out,
by a person using pencil and paper.
Algorithm must also be general to deal with any situation.

5. List out the advantages and disadvantages of algorithm.


Ans.
Advantages of Algorithms:
· It provides the core solution to a given problem.the solution can be implemented on a computer
system using any programming language of user’s choice.
· It facilitates program development by acting as a design document or a blue print of a given
problem solution.
· It ensures easy comprehension of a problem solution as compared to an equilavent computer
program.
· It eases identification and removel of logical errors in a program.
· It facilitates algorithm analysis to find out the most efficient solution to a given problem.

Dis advantages of Algorithms:


· In large algorithms the flow of program control becomes difficult to track.
· Algorithms lack visual representation of programming constructs like flowcharts; thus
understanding the logic becomes relatively difficult.
6. Explain the Algorithm with Examples ?

Ans: Algorithm:
The same problem can be solved with different methods. So, to solve a problem different
algorithms, may be accomplished. Algorithm may vary in time, space utilized. User writes
algorithm in his / her own language. So, it can not be executed on computer. Algorithm
should be in sufficient detail that it can be easily translated in to any of the languages.
Example1 : Add two numbers.
Step 1: Start
Step 2: Read 2 numbers as A and B
Step 3: Add numbers A and B and store result in C
Step 4 : Display C
Step 5: Stop
Example2: Average of 3 numbers.
1. Start
2. Read the numbers a , b , c
3. Compute the sum and divide by 3
4. Store the result in variable d
5. Print value of d
6. End

Example3: Average of n inputted numbers.


1. Start
2. Read the number n
3. Initialize i to zero
4. Initialize sum to zero
5. If i is greater than n
6. Read a
7. Add a to sum
8. Go to step 5
9. Divide sum by n & store the result in avg
10. Print value of avg
11. End

7. Explain about a Flowchart ?

Ans: Flowchart :

A flowchart is a visual representation of the sequence of steps for solving a


problem . A flowchart is a set of symbols that indicate various operations in the
program. For every process , there is a corresponding symbol in the flowchart . Once an
algorithm is written , its pictorial representation can be done using flowchart symbols. In other
words, a pictorial representation of a textual algorithm is done using a flowchart.
A flowchart gives a pictorial representation of an algorithm.
· The first flowchart is made by John Von Neumann in 1945.
· It is a symbolic diagram of operations sequence, dataflow, control flow and processing logic in
information processing.
· The symbols used are simple and easy to learn.
· It is a very helpful tool for programmers and beginners.

Purpose of a Flowchart :
 Provides Communication.
 Provides an Overview.
 Shows all elements and their relationships.
 Quick method of showing Program flow.
 Checks Program logic.
 Facilitates Coding.
 Provides Program revision.
 Provides Program documentation.

Advantages of a Flowchart :
· Flowchart is an important aid in the development of an algorithm itself.
· E asier to Understand than a Program itself.
· Independent of any particular programming language.
· Proper documentation.
· Proper debugging.
· Easy and Clear presentation.
Limitations of a Flowchart :
· Complex logic.
· Drawing is time consuming.
· Difficult to draw and remember.
· Technical detail.

8. Explain the Symbols in a Flowchart ?


Ans: Symbols : Symbols are divided in to the following two parts.
l. Auxiliary Symbols.
ll. Primary Symbols.
Some of the common symbols used in flowcharts are shown below :

Fig: Flow chart Symbols


with flowchart , essential steps of an algorithm are shown using the shapes above. The flow of
data between steps is indicated by arrows or flow lines.

9. Write an algorithm and flow chart for swapping two numbers


Ans: To Swap two integer numbers:
Algorithm : a. using third variable

Step 1 : Start
Step 2 : Input num1 , num2
Step 3 : temp = num1
Step 4 : num1 = num2
Step 5 : num2 = temp
Step 6 : Output num1 , num2
Step 7 : Stop
Algorithm : b. with out using third variable
Step 1 : Start
Step 2 : Input num1 , num2
Step 3 : calculate num1 = num1 + num2
Step 4 : calculate num2 = num1 – num2
Step 5 : calculate num1 = num1 – num2
Step 6 : Output num1 , num2
Step 7 : Stop
Flowcharts :

10. Write an algorithm and flowchart to find the largest among two numbers.
Ans:
Algorithm:

Step 1 : Start
Step 2 : Input A , B
Step 3 : if A > B then output A
else output B
Step 4 : Stop
Flowchart :
11. Write an algorithm and flowchart to find the largest among three numbers.

Algorithm: (method 1)
Step 1 : Start
Step 2 : Input A, B, C
Step 3 : if A > B go to step 4 , otherwise go to step 5
Step 4 : if A > C go to step 6 , otherwise go to step 8
Step 5 : if B > C go to step 7, otherwise go to step 8
Step 6 : print “ A is largest ” , go to step 9
Step 7 : print “ B is largest ”, go to step 9
Step 8 : print “ C is largest ” , go to step 9
Step 9 : Stop

Flowchart:

Algorithm: b.
Step 1 : Start
Step 2 : Input A, B, C
Step 3 : Let max = A
Step 4 : if B > max then max = B
Step 5 : if C > max then max = C
Step 6 : output max is largest
Step 7 : Stop
Flowchart:
12. Write an algorithm and flowchart to find factorial of a
number Hint: fact (4) = 1 * 2* 3* 4
Sol.
Alg
orithm: Step
1: Start
Step 2:
Input n
Step 3: Initialize counter variable, i , to 1 and factors
= 1 Step 4: if i <= n go to step 5 otherwise go to step
7
Step 5: calculate factors = factors * i
Step 6: increment counter variable, i, and go to
step 4 Step 7: output factors.
Step 8: stop

Flow chart:

13. Write an algorithm and flowchart to find whether a number is prime or not.

Hint: A number is said to be prime number for which the only factors are 1 and
itsel Algorithm:
Step 1: Start
Step 2: Input n
Step 3: Let i = 1,
count=0 Step 4: if i >
n/2 go to step 7
Step 5: if (n % i = = 0) count = count
+ 1 Step 6: increment i and go to step 4
Step 7: if count=2 then print “prime number” else print “not prime
number” Step 8: Stop
Flow chart:

14. Write an algorithm and flowchart to find reverse of a


number. Algorithm:
Step 1: Start
Step 2: Input
n Step 3: Let
rev=0
Step 4: if n<=0 go to
step 8 Step 5: digit =
n % 10
Step 6: rev = (rev * 10) + digit
Step 7: n = n / 10 then go to
step 4 Step 8: output rev
Step 9: Stop

15. Write an algorithm and flowchart to find the Sum of individual digits if a given number
Algorithm :-
Step 1 : Start
Step 2 : read
n Step 3 :
Sum = 0
Step 4 : While n > 0 do
4.1 : r = n % 10
4.2 : Sum = Sum + r
4.3 : n =
n/10 Step 5 : End
while
Step 6 : Write
Sum Step 7 :
Stop

Flowchart :-
16. what is the general structure of `C' program and explain with
example?
Ans: Structure of C program:

This section consists of a set of comment lines giving the name of the program, and other
details. In which the programmer would like to user later.
Ex:- /*…................................*/
Link section: Link section provides instructions to the compiler to link functions from the
system library.
Ex:- #
include<stdio.h
> #
include<conio.
h>
Definition section: Definition section defines all symbolic
constants. Ex:- # define A 10.
Global declaration section: Some of the variables that are used in more than one function
throughout the program are called global variables and declared outside of all the functions.
This section declares all the user-defined functions.
Every C program must have one main ( ) function section. This contains two parts.

i) Declaration part: This part declares all the variables used in the executable part.

Ex:- int a,b;

ii) Executable part: This part contains at least one statement .These two parts must appear
between the opening and closing braces. The program execution begins at the opening brace
and ends at the closing brace. All the statements in the declaration and executable parts end
with a semicolon (;).
Sub program section:

This section contains all the user-defined functions, that are called in the main () function.
User- defined functions generally places immediately after the main() function, although they
may appear in any order.
Ex:
17. What is a variable? and write the rules for constructing variable?

Variables: It is a data name that may be used to store a data value. It cont be changed during
the execution of a program. A variable may taken different values at different times during
execution.
Rules: Variable names may consist of letters, digits and under score( _ ) character.

 First char must be an alphabet or an ‘-’


 Length of the variable cont exceed upto 8 characters, some C compilers
can be recognized upto 31 characters.
 No , and no white space, special symbols allowed.
 Variables name should not be a keyword.
 Both upper & lower case letters are
used. Ex:- mark,sum1,tot-
value,delhi valid
Prics$, group one, char invalid

18. How to declare and initialize a


variable? Declaration does two things:
1. It tells the compiler what the variable name is.
2. It specifies what type of data the variable will hold.

The declaration of variables must be done before they are used in the program.

The syntax for declaring a variable is as follows:

Data-type v1,v2,…….,vn;

V1,v2,…vn are the names of variables. Variables are separated by commas. A declaration
statement must end with a semicolon. For example , valid declarations are:

int count;

int number,
total; double
ratio;
The simplest declaration of a variable is shown in the following code fragment:

Ex:

main()/*…………….Program Name…..................*/

/*……………….Declaration..........................................*/

float
x,y;
int
code;
short int
count; long
int amount;
double
deviation;
unsigned n;
char c;

/*…………………………Computation........................................ */

/*…………………………Program ends..............................*/

Initialization of variable :

Initialize a variable in c to assign it a starting value. Without this we can't get whatever
happened to memory at that moment.

C does not initialize variables automatically. So if you do not initialize them properly,
you can get unexpected results. Fortunately, C makes it easy to initialize variables when
you declare them.

For Example :

int x=45;

int month_lengths[] = {23,34,43,56,32,12,24};

struct role = { "Hamlet", 7, FALSE, "Prince of Denmark ", "Kenneth Branagh"};

Note : The initialization of variable is a good process in programming.

19. Explain data types in ‘C’?

DATA TYPES

Data type is the type of the data that are going to access within the program. C supports
different data types. Each data type may have pre-defined memory requirement and storage
representation. C supports 4 classes of data types.
1. Primary or (fundamental) data type(int, char, float, double)
2. User-defined data type(type def)
3. Derived data type(arrays, pointers, structures, unions)
4. Empty data type(void)- void type has no value.
1 byte = 8 bits (0’s and 1’s)
1. Primary or (fundamental) data type

All C compilers support 4 fundamentals data types, they are

i) Integer (int)
ii) Character(char)
iii) Floating (float)
iv) Double – precision floating point(double)

1. Integer types:

Integers are whole numbers with a range of values supported by a particular machine.
Integers occupy one word of storage and since the word size of the machine vary. If we use
16 bit word length the size of an integer value is -32768 to +32767. In order to control over
the range of numbers and storage space, C has 3 classes of integer storage, namely short,
long, and unsigned.

DATA TYPES RANGE Size Control string


-215 to 215 -1
Int 2 bytes %d (or) %i
-32768 to +32767

-128 to +127 1 byte %d (or) %i


Signed short int(or)
short int
%d (or) %i
Unsigned short int 0 to 255 1 byte

unsigned int 0 to 65’535 2 bytes %u


Un signed long int 0 to 4’294’967’295 4 bytes
long int (or)signed -2147483648 to
4 bytes %ld
long int +2147483647
long unsigned int 0 to 4294967295 4 bytes %lu

2. Character type:-

Single character can be defined as a character (char) type data. Characters are usually stored
in 8 bits of internal storage. Two classes of char types are there.
Signed char, unsigned char.
Signed char(or) char  1 byte- -128 to +127%c
Unsigned char 1 byte 0 to 255%c
3. Floating point types:

Floating point (real) numbers are stored in 32 bits, with 6 digits of precision when accuracy
provided by a float number is not sufficient
Float  4 bytes3.4e-38 to 3.4e+38%f

4.Double precision type:

Double data type number uses 64 bits giving a precision of 14 digits. These are known as
double precision no.s. Double type represents the same data type that float represents, but
with a greater precision. To extend the precision further, we may we long double which uses
80 bits.
double 8 bytes  1.7e-308 to 1.7e+308%lf
long double 10 bytes  3.4e-4932 to
1.1e+4932 %lf
2. User defined data types:

C –supports a feature known as “type definition” that allows users define an identifier that
would represents an existing type.
Ex:- typedef data-type identifier;

Where data-type indicates the existing datatype

Identifier indicates the new name that is given to the data


type. Ex:- typedef int marks;
Marks m1, m2, m3;

typedef cont create a new data type ,it can rename the existing datatype. The main
advantage of typedef is that we can create meaningful datatype names for increasing the
readability of the program.
Another user-defined datatype is “enumerated data
type(enum)” Syntax: enum identifier{value1, value2,…
valuen};
Where identifier is user-defined datatype which is used to declare variables that can have one
of the values enclosed within the braces. Value1 ,value2,.valuen all these are known as
enumeration constants.
Ex:- enum identifier v1, v2,……vn

V1=value3;
V2=value1;…
……
Ex:- enum day {Monday,Tuesday..................sunday};
Enum day week-f,week-end

Week-f = Monday
-
-
-
-
(or)
enum day{Monday…Sunday}week-f, week-end;
20. (a) Describe the different types of constants in C with example?
(b) What are the rules for creating C constants explain with example?

TYPES OF C CONSTANTS
1. Integer constants
2. Real constants
3. Character constants
4. String constants

1. Integer constants: An integer constant refers to a sequence of digits. There are three
types of integers, namely, decimal integer, octal integer and hexadecimal integer.
Examples of Integer Constant:
426 ,+786 , -34(decimal integers)

037, 0345, 0661(octal integers)

0X2, 0X9F, 0X (hexadecimal integers)

2. Real constants: These quantities are represented by numbers containing fractional parts like
18.234. Such numbers are called real (or floating point) constants.
Examples of Real Constants:
+325.34
426.0
-32.67 etc.
The exponential form of representation of real constants is usually used if the value of the
constant is either too small or too large. In exponential form of representation the Real
Constant is represented in two parts. The first part present before 'e' is called Mantissa and
the part following 'e' is called Exponent.
For ex. .000342 can be written in Exponential form as 3.42e-4.

3. Single Character constants: Single character constant contains a single character


enclosed within a pair of single quote marks.

For ex. 'A',’5’,’;’,’ ‘

Note that the character constant’5’ is not same as the number 5. The last constant is a blank
space.Character constant has integer values known as ASCII values. For example, the statement
Printf(“%d”,a); would print the number 97,the ASCII value of the letter a. Similarly, the
statement printf(“%c”,97); would output the letter ‘a’
String constants: A string constant is a sequence of character enclosed in double quotes. the
characters may be letters, numbers, special characters and blank space.
Examples are:

“HELL
O!”
“1979”
“welco
me” “?
..........!”
“5+3”
“X”

RULES OF CONSTRUCTING INTEGER CONSTANTS


a. an integer constant must have at least one digit.
b. It must not have a decimal point.
c. It can be either positive or negative.
d. The allowable range for constants is -32768 to 32767
In fact the range of integer constants depends upon
compiler. For ex. 435
+786
-7000
RULES OF CONSTRUCTING REAL CONSTANTS
a. A real constants must have at least one digit
b. it must have a decimal point.
c. it could be either positive or negative.
d. default sign is
positive. For ex.
+325.34
426.0
In exponential form of representation, the real constants is represented in two parts. The part
appearing before ‘e’ is called mantissa where as the part following ‘e’ is called exponent.
Range of real constants expressed in exponential form is -3.4e38 to
3.4e38. Ex. +3.2e-5
RULES OF CONSTRUCTING CHARACTER CONSTANTS
a. a character constant is a single alphabet, a single digit or a single special symbol
enclosed within single inverted commas.
b. The maximum length of character constant can be one
character. Ex `A`
21. What is an operator and List different categories of C operators based on
their functionality? Give examples?
Operators:
An operator is a symbol performs certain mathematical or logical manipulations. Operators
are used in programs to manipulate data variables.
C operators can be classified into a number of categories, they are

1. Arithmetic Operators

2. Relational Operators

3. Logical Operators

4. Assignment Operators

5. Increment and decrement operators

6. Conditional operators

7. Bitwise Operators

8. Special operators

1. Arithmetic Operators:
The arithmetic operators are

Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo division

Here a and b are operands, assign values for a=14 and b=4 we have the following
results a-b = 10
a+b = 18

a*b = 56
a/b =
3(coefficient)
a%b =
2(remainder)
2.Relational Operators:
Relational operators are used for comparing two quantities, and take certain decision. For
example we may compare the age of two persons or the price of two items….these
comparisons can be done with the help of relational operators.

An expression containing a relational operator is termed as a relational expression. The


value of a relational expression is either one or zero. It is one if the specified relation is true
and zero if the relation is false.

Ex:- 13<34 (true)

23>35(false) C supports 6
relational operators
Operator Meaning
< is less than
<= is less than or equal to
> is greater than t
>= is greater than or equal to
== is equal to
!= is not equal to

Ex:- 4.5<=10(true)

6.5<-10(false)
10<4+12(true)
When arithmetic expression are used on either side of a relational operator, the arithmetic
expression will be evaluated first and then the results compared, that means arithmetic
operators have a higher priority over relational operators.

3. Logical Operator:

C has 3 logical operators. The logical operators are used when we want to test more than one
condition and make decisions.

Operator Meaning
&& Logical AND
|| Logical OR
! LogicalNOT
The logical operators && and || are used when we test more than one condition and make decisions.

Ex:- a>b && x==45

This expression combines two or more relational expressions, is termed as a logical


expression or a compound relational expression. The logical expression given above is true
only if a>b is true and x==10 is true. if both of them are false the expression is false.

OP1 OP2 && ||


0 0 0 0
0 1 0 1
1 0 0 1
1 1 1 1

Some examples of logical expression

1. if (age >55 && salary<1000)


2. if(number<0 || number>100)

4. Assignment operator:

These operators are used to assign the result of an expression to a variable. The usual
assignment operator is ‘=’

V op = exp;

Where v is a variable, exp is an expression and op is a C binary arithmetic operator. The


operator op=is known as the shorthand assignment operator.

The assignment statement is V


op=exp; Ex:- X= X+(Y+1);
a*=a;----- a=a*a;

5. Increment and Decrement operator:

++ and - - are increment and decrement operators in C. The operator ++ adds 1 to the
operand, while - - subtracts 1.both are unary operators.
++m; or m++; is equal to m=m+1(m+=1;)

--m; or m- - is equal to m=m-1(m- = 1;)

We use the increment and decrement statements in for and while loops
extensively. Ex:- m=5;
Y=++m; the value of y=6 and m =6.

Suppose if we write the above statement as

m=5; y= m++; the value of y=5 and m=6.

A prefix operator first adds 1 to the operand and then the result is assigned to the variable on
left. On the other hand, a postfix operator first assigns the value to the variable on left and
then increments the operand.

6. Conditional operator:

A ternary operator pair”? :” is available in C to construct conditional expressions of the


form exp ? exp : exp3
Where exp1,exp2 and exp3 are expressions,

The operator?: works as follows: exp1 is evaluated first. If it is non-zero (true), then the
expression exp 2 is evaluated and becomes the value of the expression. If exp1 is false, exp3
is evaluated and its value becomes the value of the expression.

Ex:- a=10; b=45;

X = (a>b) ?
a:b; o/p:- X value
of b (45).
7. Bitwise Operator:
C supports a special operator knows as bitwise operators for manipulation of data at bit
level. These operators are used for testing the bits, or shifting them right to left. Bitwise
operators may not be applied to float or double.

Operator Meaning
& Bitwise AND
| Bitwise OR

ꞈ Bitwise exclusive OR

<< Shift left


>> Shift right

8. Special operators:

C supports some special operators such as comma operator, size of operator, pointer operator
(& and *) and member selection operators (. and -> ).

The comma operator: The comma operator is used to link the related expression together.
A comma linked list of expressions is evaluated left to right and the value of right- most
expression is the value of the combined expression. For example, the statement
Value = (x=10, y=5, x+y);
In for loops: for (n=1 , m=10, n<=m; n++, m++);
The sizeof operator: The sizeof is a compile time operator and when used with an operand,
it returns the number of bytes the operand occupies. The operand may be variable, a constant
or a data type qualifier.
m = sizeof (sum);
n = sizeof (long int);
The sizeof operator is normally used to determine the lengths of arrays and structures when
their sizes are not known to the programmer. It is also used to allocate memory space
dynamically to variables during execution of a program.

22. Explain the types of type conversions in C with example?


Type conversions: converting a variable value or a constant value temporarily from one data
type to other data type for the purpose of calculation is known as type conversion.
There are two types of conversions
1. automatic type conversion (or) implicit
2. casing a value (or) explicit
1. Implicit: In this higher data type can be converted into lower data type.
* Float value can be converted into integral value by removing the fractional part.
* Double value can be converted into float value by rounding of the digits.
* Long int can be converted into int value by removing higher order bits.
2. Explicit: In this type of conversion, the programmer can convert one data type to other
data type explicitly.
Syntax: (datatype) (expression)
Expression can be a constant or a variable
Ex: y = (int) (a+b)
y=
cos(double(x))
double a = 6.5
double b = 6.5
int result = (int) (a) + (int)
(b) result = 12 instead of
13.
 int a=10
float(a)->10.00000

23. Define an expression? How can you evaluate an expression?


Expressions:

An expression in C is some combination of constants, variables,


operators and function calls.
Sample expressions are:a + b tan(angle)
• Most expressions have a value based on their contents.

• A statement in C is just an expression terminated with a


semicolon. For example:
sum = x + y + z;
printf("Go
Buckeyes!");
The rules given below are used to evaluate an expression,

1) If an expression has parenthesis, sub expression within the parenthesis is


evaluated first and arithmetic expression without parenthesis is evaluated first.
2) the operators high level precedence are evaluated first.

3) the operators at same precedence are evaluated from left to right or


right to left depending on the associativity of operators.
Expressions are evaluated using an assignment statement of the form:
variable = expression;
Variable is any valid C variable name. when the statement is encountered, the expression is
evaluated first and the result then replaces the previous value of the variable on the left-hand
side. All variables used in the expression must be assigned values before evaluation is
attempted.
Ex:- x = a*b-c;
Y = b/c*a;

Z = a-b / c+d;

Ex:- x= a-b/3+c*2-1 when a=9, b=12, and c=3 the expression


becomes. x = 9-12/3 +3*2-1
Step1: x = 9-4+3*2-1
Step2: x = 9-4+6-1
Step3: x = 5+6-
1 Step4: x = 11-
1 Step5: x = 10
24. Define precedence and associativity? Give an example?
or
Explain the hierarchy (priority) and associativity(clubbing)of operators in ‘C’ with
example?

Operator Precedence:

Various relational operators have different priorities or precedence. If an arithmetic


expression contains more operators then the execution will be performed according to their
properties. The precedence is set for different operators in C.

Type of operator Operators Associativity


Unary operators +,-,!,++,--,type, ˜,size of Right to left
Arithmetic operators *, /,%,+,- Left to right
Bit – manipulation operators <<,>> Left to right
Relational operators >,<,>=,<=,==,!= Left to right
Logical operators &&,|| Left to right
Conditional operators ?,: Left to right
Assignment operators =,+=,-=,*=,/=,%= Right to left
 Precedence rules decide the order in which different operators are applied
 Associativity rule decides the order in which multiple occurrences of the same level
operator are applied.
25. (a) Explain the formatted I/O functions with example? (8)
(b) Explain unformatted (character oriented) I/O functions with example?(7)
Managing input and output operations:
Reading, processing and writing of data are the three essential functions of a computer program.
Most programs take some data as input and display the processed data. We have two methods
of providing data to the program variables. One method is to assign values to variables
through the assignment statements like x=5, a=0 and so on. Another method is to use the
input function scanf, which can read data from a keyboard. We have used both the
methods in programs. For
outputting results, we have used extensively the function printf, which sends results out to a
terminal.
Input – Output functions:-
 The program takes some I/P- data, process it and gives the O/P.
 We have two methods for providing data to the program
i) Assigning the data to the variables in a program.
ii) By using I/P-O/P statements.
C language has 2 types of I/O statements; all these operations are carried out through
function calls.
1. Unformatted I/O statements
2. Formatted I/O statements

Unformatted I/O statements:-


getchar( ):- It reads single character from standard input device. This function don’t require any
arguments.
Syntax:- char variable_name =
getchar( ); Ex:- char x;
x = getchar( );
putchar ( ):- This function is used to display one character at a time on the standard output
device.
Syntax:-
putchar(char_variable); Ex:-
char x;
Putchar
(x); Ex:-
main( )
{
Char ch;
Printf(“enter a char”);
Ch = getchar( );
Printf(“enter char is”);
Putchar(ch);
}
getc() :- This function is used to accept single character from the
file. Syntax: char variable_name = getc();
Ex:- char c;
c = getc();
putc():- This function is used to display single
character. Syntax:- putc(char variable_name);
Ex:-
charc;
Putc(c)
;
These functions are used in file processing.

gets( ):- This function is used to read group of characters(string) from the standard I/P
device. Syntax:- gets(character array variable);
Ex:- gets(s);
Puts( ):- This function is used to display string to the standard O/P
device. Syntax:- puts(char array variables);
Ex:- puts(s);
Ex:- main()
{
char s[10];
Puts(“enter
name”);
gets(s);
puts(“print
name”);
puts(s);
}
getch():- This function reads single character directly from the keyboard without displaying
on the screen. This function is used at the end of the program for displaying the output
(without pressing (Alt-F5).
Syntax: char variable_name = getch();
Ex:- char c
c = getch();
getche():- This function reads single character from the keyboard and echoes(displays) it to the
current text window.
Syntax:- char variable_name = getche();
Ex:- char c
c=
getche(); ex:-
main()
{
char ch, c;
Printf(“enter
char”); ch =
getch();
printf(“%c”,
ch);
printf(“enter
char”); c =
getche();
printf(“%c”,c);
}
O/P:- enter character a
Enter character b
b

Ex:-
main()
{
Char a;
Printf(“enter
char”); a =
getchar();
if (isupper(a))
{
x=
tolower(a)
;
putchar(x)
;
}
else
putchar(toupper(a));
}
O/P:- enter char A
a

Formatted I/O Functions: Formatted I/O refers to input and output that has been arranged in a
particular format.

Formatted I/P functions  scanf( ) ,


fscanf() Formatted O/P functions---
printf() , fprintf()
scanf( ) :- scanf() function is used to read information from the standard I/P
device. Syntax:- scanf(“controlstring”, &variable_name);
Ex:- int n;
Scanf(“%d”,n);
Control string represents the type of data that the user is going to accept. & gives the address
of variable.(char-%c , int-%d , float - %f , double-%lf). Control string and the variables going
to I/P should match with each other.
Simple format specification as follows
%w type – specified ex:- %4d , %6c…………
Here ‘w’ represents integer value specifies total number of
columns. Ex:- scanf(“%5d”,&a); a = 4377
4 3 7 7
Printf( ): This function is used to output any combination of data. The outputs are produced
in such a way that they are understandable and are in an easy to use form. It is necessary for
the programmer to give clarity of the output produced by his program.
Syntax:- printf(“control string”, var1,var2……);

UNIT-II

1. What are different types of ‘if’ statements available in c? Explain them.


(Or)
Describe all the variants of if-else statement with clear syntax and examples.
A. There are 4 if statements available in C:
1. Simple if statement.
2. if…else statement.
3. Nested if…else statement.
4. else if ladder
1. Simple if statement
Simple if statement is used to make a decision based on the available choice. It has the following
form:
Syntax:
if ( condition )
{
Stmt block;
}
Stmt-x;
In this syntax,
· If is the keyword. <condition> is a relational expression or logical expression or any expression
that returns either true or false. It is important to note that the condition should be enclosed
within parentheses ‘(‘ and ’ )’.
· The stmt block can be a simple statement or a compound statement or a null statement.
· Stmt-x is any valid C statement.
· The flow of control using simple if statement is determined as follows:

Whenever simple if statement is encountered, first the condition is tested. It returns either true or
false. If the condition is false, the control transfers directly to stmt-x with out considering the stmt
block. If the condition is true, the control enters into the stmt block. Once, the end of stmt block is
reached, the control transfers to stmt-x
Example Program:
PROGRAM FOR IF STATEMENT:
#include<stdio.h>
#include<conio.h> int
main()
{
int age;
printf("enter age\n");
scanf("%d",&age);
if(age>=55)
printf("person is retired\n"); getch();
}

2. If—else statement
if…else statement is used to make a decision based on two choices. It has the following form:
syntax:
if(condition)
{
True Stmt block;
}
Else
{
False stmt block;
}
Stmt-x;
In this syntax,
· If and else are the keywords.
· <condition> is a relational expression or logical expression or any expression that returns either
true or false. It is important to note that the condition should be enclosed within parentheses
( and ).
· The true stmt block and false stmt block are simple statements or compound statements or null
statements.
· Stmt-x is any valid C statement.
The flow of control using if...else statement is determined as follows:

Whenever if...else statement is encountered, first the condition is tested. It returns either true or
false. If the condition is true, the control enters into the true stmt block. Once, the end of true stmt
block is reached, the control transfers to stmt-x without considering else-body.
If the condition is false, the control enters into the false stmt block by skipping true stmt block.
Once, the end of false stmt block is reached, the control transfers to stmt-x.
Example Program:
PROGRAM FOR IF ELSE STATEMENT:
#include<stdio.h>
#include<conio.h> int
main()
{
int age;
printf("enter age\n");
scanf("%d",&age);
if(age>=55)
printf("person is retired\n");
else
printf("person is not retired\n");
getch();
}
3. Nested If—else statement
Nested if…else statement is one of the conditional control-flow statements. If the body of if
statement contains at least one if statement, then that if statement is called as “Nested if…else
statement”. The nested if…else statement can be used in such a situation where at least two
conditions should be satisfied in order to execute particular set of instructions. It can also be used to
make a decision among multiple choices. The nested if…else statement has the following form:
Syntax: If(condition1)
{
If(condition 2)
{
Stmt1
}
Else
{
Stmt 2
}
}
Else
{
Stmt 3;
}
Stmt-x;
In this syntax,
· if and else are keywords.
· <condition1>,<condition2> … <condition> are relational expressions or logical expressions or
any other expressions that return true or false. It is important to note that the condition should be
enclosed within parentheses ( and ).
· If-body and else-body are simple statements or compound statements or empty statements.
· Stmt-x is a valid C statement.
The flow of control using Nested if...else statement is determined as follows:

Whenever nested if…else statement is encountered, first <condition1> is tested. It returns


either true or false.
If condition1 (or outer condition) is false, then the control transfers to else-body (if exists) by
skipping if-body.
If condition1 (or outer condition) is true, then condition2 (or inner condition) is tested. If the
condition2 is true, if-body gets executed. Otherwise, the else-body that is inside of if statement gets
executed.
Example Program:
PROGRAM FOR NESTED IF… ELSE STATEMENT:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
printf("enter three values\n");
scanf("%d%d%d",&a,&b,&c);
if(a>b)
{
if(a>c)
printf("%d\n",a); else
printf("%d\n",b);
}
else
{
if(c>b)
printf("%d\n",c); else
printf("%d\n",b);
}
getch();
}

4. Else—if Ladder
Else if ladder is one of the conditional control-flow statements. It is used to make a decision among
multiple choices. It has the following form:
Syntax:
If(condition 1)
{
Statement 1;
}
Else if(condition 2)
{
Statement 2;
}
Else if(condition 3)
{
Statement 3;
}
Else if(condition n)
{
Statement n;
}
Else
{
Default Statement;
}
Stmt- x;
In this syntax,
· if and else are keywords. There should be a space between else and if, if they come together.
· <condition1>,<condition2>….<condtionN> are relational expressions or logical expressions or
any other expressions that return either true or false. It is important to note that the condition
should be enclosed within parentheses ( and ).
· Statement 1, statement 2,statement 3……,statement n and default statement are either simple
statements or compound statements or null statements.
· Stmt-x is a valid C statement.
The flow of control using else--- if Ladder statement is determined as follows:

Whenever else if ladder is encountered, condition1 is tested first. If it is true, the statement 1
gets executed. After then the control transfers to stmt-x.

If condition1 is false, then condition2 is tested. If condition2 is false, the other conditions are
tested. If all are false, the default stmt at the end gets executed. After then the control transfers to
stmt-x.
If any one of all conditions is true, then the body associated with it gets executed. After then the
control transfers to stmt-x.
Example Program:
PROGRAM FOR THE ELSE IF LADDER STATEMENT:
#include<stdio.h>
#include<conio.h>
void main()
{
int m1,m2,m3,avg,tot; printf("enter
three subject marks");
scanf("%d%d%d", &m1,&m2,&m3);
tot=m1+m2+m3;
avg=tot/3; if(avg>=75)
{
printf("distinction");
}
else if(avg>=60 && avg<75)
{
printf("first class"); }
else if(avg>=50 && avg<60)
{
printf("second class");
}
else if (avg<50)
{
printf("fail");
}
getch(); }

2. Explain the switch statement with Example program.


switch statement:
switch statement is one of decision-making control-flow statements. Just like else if ladder, it is also
used to make a decision among multiple choices. switch statement has the following form:
switch(<exp>)
{
case <exp-val-1>: statements block-1
break;
case <exp-val-2>: statements block-2
break;
case <exp-val-3>: statements block-3
break;
:
:
case <exp-val-N>: statements block-N
break;
default: default statements block
}
Next-statement; In this syntax,
· switch, case, default and break are keywords.
· <exp> is any expression that should give an integer value or character value. In other words, it
should never return any floating-point value. It should always be enclosed with in parentheses
( and ). It should also be placed after the keyword switch.
· <exp-val-1>, <exp-val-2>, <exp-val-3>…. <exp-val-N> should always be integer constants or
character constants or constant expressions. In other words, variables can never be used as <exp-
val>. There should be a space between the keyword case and <exp-val>. The keyword case
along with its <exp-val> is called as a case label. <exp-val> should always be unique; no
duplications are allowed.
· Statements block-1, statements-block-2, statements block-3… statements block-N and default
statements block are simple statements, compound statements or null statements. It is important
to note that the statements blocks along with their own case labels should be separated with a
colon ( : ).
· The break statement at the end of each statements block is an optional one. It is recommended
that break statement always be placed at the end of each statements block. With its absence, all
the statements blocks below the matched case label along with statements block of matched case
get executed. Usually, the result is unwanted.
· The statement block and break statement can be enclosed with in a pair of curly braces { and }.
· The default along with its statements block is an optional one. The break statement can be placed
at the end of default statements block. The default statements block can be placed at any where
in the switch statement. If they placed at any other places other than at end, it is compulsory to
include a break statement at the end of default statements block.
· Next-statement is a valid C statement.

Whenever, switch statement is encountered, first the value of <exp> gets matched with case
values. If suitable match is found, the statements block related to that matched case gets executed.
The break statement at the end transfers the control to the Next-statement.
If suitable match is not found, the default statements block gets executed. After then the control
gets transferred to Next-statement.
Example Program:
#include<stdio.h>
void main()
{
int a,b,c,ch;
clrscr();
printf("\nEnter the choice:");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("\nEnter two numbers :");
scanf("%d%d",&a,&b);
c=a+b;
break;
case 2: printf("\nEnter two numbers :");
scanf("%d%d",&a,&b);
c=a-b;
break;
case 3: printf("\nEnter two numbers :");
scanf("%d%d",&a,&b);
c=a*b;
break;
case 4: printf("\nEnter two numbers :");
scanf("%d%d",&a,&b);
c=a/b;
break;
case 5:return;
}
printf("\nThe result is: %d",c);
getch();
}

3. Write in detail about different types of loop statements in C.


While:
The simplest of all the loopiung structures in c is the while statement.The basic format of the while
statement is:
Syntax:
While(condition)
{
Statements;
}
The while is an entry –controlled loop statement.The condition is evaluated and if the condition is
true then the statements will be executed.After execution of the statements the condition will be
evaluated and if it is true the statements will be executed once again.This process is repeated until
the condition becomes false and the control is transferred out of the loop .On exit the program
continues with the statement immediately after the body of the loop.
Flow chart:
Example Program:
WHILE: PRINT N NATURAL NUMBERS
#include<stdio.h>
#include<conio.h> int
main()
{
int i,n;
printf("enter the range\n");
scanf("%d",&n);
i=1;
while(i<=n)
{
printf("%d",i);
i=i+1;
}
getch();
}

do-while statement:
It is one of the looping control statements. It is also called as exit-controlled looping control
statement. i.e., it tests the condition after executing the do-while loop body.
The main difference between “while” and “do-while” is that in “do-while” statement, the loop body
gets executed at least once, though the condition returns the value false for the first time, which is
not possible with while statement. In “while” statement, the control enters into the loop body when
only the condition returns true.
Syntax:
Initialization statement;
do
{ statement(s);
} while(<condition>);
next statement;
While and do are the keywords. <condition> is a relational expression or a compound relational
expression or any expression that returns either true or false. initialization statement, statement(s)
and next_statement are valid ‘c’ statements. The statements with in the curly braces are called as do-
while loop body. The updating statement should be included with in the do-while loop body. There
should be a semi-colon (;) at the end of while(<condition>).

Whenever “do-while” statement is encountered, the initialization statement gets executed


first. After then, the control enters into do-while loop body and all the statements in that body will be
executed. When the end of the body is reached, the condition is tested again with the updated loop
counter value. If the condition returns the value false, the control transfers to next statement with out
executing do-while loop body. Hence, it states that, the do-while loop body gets executed for the first
time, though the condition returns the value false.
Example Program:
DO WHILE:
#include<stdio.h>
#include<conio.h> int
main()
{
int i,n;
printf("enter the range\n");
scanf("%d",&n);
i=1;
do
{
printf("%d\n",i);
i=i+1;
}
while(i<=n);
getch();
}
for statement:
It is one of the looping control statements. It is also called as entry-controlled looping control
statement. i.e., it tests the condition before entering into the loop body. The syntax for “for”
statement is as follows:
Syntax:
for(exp1;exp2;exp3)
for-body
next_statement;

In this syntax,
for is a keyword. exp1 is the initialization statement. If there is more than one statement, then those
should be separated with commas. exp2 is the condition. It is a relational expression or a compound
relational expression or any expression that returns either true or false. The exp3 is the updating
statement. If there is more than one statement, then those should be separated with commas. exp1,
exp2 and exp3 should be separated with two semi-colons. exp1, exp2, exp3, for- body and
next_statement are valid ‘c’ statements. for-body is a simple statement or compound statement or a
null statement.

Whenever “for” statement is encountered, first exp1 gets executed. After then, exp2 is tested. If
exp2 is true then the body of the loop will be executed otherwise loop will be terminated.
When the body of the loop is executed the control is transferred back to the for statement after
evaluating last statement in the loop.now exp3 will be evaluated and the new value is again
tested .if it satisfies body of the loop is executed .This process continues till condition is false.
Example Program:
FOR LOOP:
#include<stdio.h>
#include<conio.h>
void main()
{
int i,n;
printf("enter the value");
scanf("%d",&n); for(i=1;i<=n;i++)
{
printf("%d\n",i);
}
getch();
}

4. Explain Jumping control-flow statements.


(Or)
Explain the differentiate between the following with example?
a) Break statement
b) Continue statement
c) Goto statement

Jumping control-flow statements are the control-flow statements that transfer the control to the
specified location or out of the loop or to the beginning of the loop. There are 3 jumping control
statements:

1. break statement
The “break” statement is used with in the looping control statements, switch statement and nested
loops. When it is used with the for, while or do-while statements, the control comes out of the
corresponding loop and continues with the next statement.
When it is used in the nested loop or switch statement, the control comes out of that loop / switch
statement within which it is used. But, it does not come out of the complete nesting.
The syntax for the “break” statement is:

break;
In this syntax, break is the keyword. The following diagram shows the transfer of control when
break statement is used:
Any loop
{
statement_1;
statement_2;
:
break;
:
}
next_statement
Example Program:
BREAK STATEMENT:
#include<stdio.h>
#include<conio.h> int
main()
{
int i;
for(i=1; i<=10; i++)
{
if(i==6) break;
printf("%d",i);}
getch();
}
2.continue statement
A continue statement is used within loops to end the execution of the current iteration and proceed to
the next iteration. It provides a way of skipping the remaining statements in that iteration after the
continue statement. It is important to note that a continue statement should be used only in loop
constructs and not in selective control statements. The syntax for continue statement is:

continue;

where continue is the keyword. The following diagram shows the transfer of control when continue
statement is
used:
Any loop
{
statement_1;
statement_2;
:
continue;
:
}
next_statement

Example Program: CONTINUE


STATEMENT:
#include<stdio.h>
#include<conio.h> int
main()
{
int i, sum=0, n; for(i=1;
i<=10; i++)
{
printf("enter any no:");
scanf("%d",&n); if(n<0)
continue; else
sum=sum+n;
printf("%d\n",sum);
}
getch();
}
3. goto statement

The goto statement transfers the control to the specified location unconditionally. There are certain
situations where goto statement makes the program simpler. For example, if a deeply nested loop is
to be exited earlier, goto may be used for breaking more than one loop at a time. In this case, a break
statement will not serve the purpose because it only exits a single loop.

he syntax for goto statement is:


label:
{
statement_1;
statement_2;
:
}
:
goto label;
In this syntax, goto is the keyword and label is any valid identifier and should be ended with a colon
(:).
The identifier following goto is a statement label and need not be declared. The name of the
statement or label can also be used as a variable name in the same program if it is declared
appropriately. The compiler identifies the name as a label if it appears in a goto statement and as a
variable if it appears in an expression.

If the block of statements that has label appears before the goto statement, then the control
has to move to backward and that goto is called as backward goto. If the block of statements that has
label appears after the goto statement, then the control has to move to forward and that goto is called
as forward goto.
Example Program:
PROGRAM FOR GOTO STATEMENT:
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf("www."); goto x;
y: printf("expert");
goto z; x:
printf("c programming");
goto y;
z:
printf(".com"); getch();
}

5. What are the differences between break statement and Continue statement?
The break statement will immediately jump to the end of the current block of code.
The continue statement will skip the rest of the code in the current loop block and will return to the
evaluation part of the loop. In a do or while loop, the condition will be tested and the loop will keep
executing or exit as necessary. In a for loop, the counting expression (rightmost part of the for loop
declaration) will be evaluated and then the condition will be tested. Take the

following example:

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

if (i==5) continue;
printf("%d",i); if
(i==8) break;
}

This code will print 1 to 8 except 5.

Continue means, whatever code that follows the continue statement WITHIN the loop code
block will not be exectued and the program will go to the next iteration, in this case, when the
program reaches i=5 it checks the condition in the if statement and executes 'continue', everything
after continue, which are the printf statement, the next if statement, will not be executed.

Break statement will just stop execution of the look and go to the next statement after the loop
if any. In this case when i=8 the program will jump out of the loop. Meaning, it wont continue till
i=9,10.

break is also used in switch-case statements to delimit the different cases.


6. What are the differences between break statement and exit ?
Break exit()

1) It is used to come out of loop or switch 1) It is used to come out of entire program.
or block in which it is placed.

2) It is a keyword. Its definition has already 2) It is a pre-defined function that is


defined by language developers. available in process.h or stdlib.h header
files. It takes an argument: 0 or 1. exit(0)
means a clean exit without an error
message. exit(1) means an abrupt exit with
an error message.

7. What are the differences between while and do-while statements ?

The main difference between the while and do-while loop is in the place where the condition is to be
tested.
In the while loops the condition is tested following the while statement then the body gets
executed. Where as in do-while, the condition is checked at the end of the loop. The do-while loop will
execute at least one time even if the condition is false initially. The do-while loop executes until the
condition becomes false.

while do-while

1) It is an entry-controlled control-flow statement. 1) It is an exit-controlled control-flow statement.


That is, it tests condition before the body gets That is, it tests condition after the body gets
executed. executed.

2) The body gets executed only when the condition 2) The body gets executed at least once though the
is true. condition is false for the first time.

8. What is an array? How to declare and initialize arrays? Explain with examples
Array:-
An array is defined as an ordered set of similar data items. All the data items of an array are stored
in consecutive memory locations in RAM. The elements of an array are of same data type and each
item can be accessed using the same name.
Declaration of an array:- We know that all the variables are declared before the are used in the
program. Similarly, an array must be declared before it is used. During declaration, the size of the
array has to be specified. The size used during declaration of the array informs the compiler to
allocate and reserve the specified memory locations.
Syntax:- data_type array_name[n];
where, n is the number of data items (or) index(or) dimension.
0 to (n-1) is the range of array.
Ex: int a[5];
float x[10];
Initialization of Arrays:-
The different types of initializing arrays:
1. At Compile time
(i) Initializing all specified memory locations.
(ii) Partial array initialization
(iii) Initialization without size.
(iv) String initialization.
2. At Run Time
1. Compile Time Initialization
We can initialize the elements of arrays in the same way as the ordinary variables when they are
declared. The general form of initialization of arrays is
Type array-name[size]={ list of values};
(i) Initializing all specified memory locations:- Arrays can be initialized at the time of
declaration when their initial values are known in advance. Array elements can be initialized
with data items of type int, char etc.
Ex:- int a[5]={10,15,1,3,20};
During compilation, 5 contiguous memory locations are reserved by the compiler for the variable a
and all these locations are initialized as shown in figure.

Fig: Initialization of int Arrays


Ex:-
int a[3]={9,2,4,5,6};//error: no. of initial vales are more than the size of array.
(ii) Partial array initialization:- Partial array initialization is possible in c language. If the
number of values to be initialized is less than the size of the array , then the elements will be
initialized to zero automatically.
Ex:-
int a[5]={10,15};
Eventhough compiler allocates 5 memory locations, using this declaration statement; the compiler
initializes first two locations with 10 and 15, the next set of memory locations are automatically
initialized to 0's by compiler as shown in figure.

Fig: Partial Array Initialization


Initialization with all
zeros:- Ex:-int a[5]={0};

(iii) Initialization without size:- Consider the declaration along with the initialization.
Ex:-
char b[]={'C','O','M','P','U','T','E','R'};
In this declaration, eventhough we have not specified exact number of elements to be used in array

b, the array size will be set of the total number of initial values specified. So, the array size will be
set to 8 automatically. the array b is initialized as shown in figure.

Fig: Initialization without size


Ex:- int ch[]={1,0,3,5} // array size is 4
(iv) Array initialization with a string: - Consider the declaration with string initialization.
Ex:-
char b[]="COMPUTER";
The array b is initialized as shown in figure.

Fig: Array Initialized with a String


Eventhough the string "COMPUTER" contains 8 characters, because it is a string. It always ends
with null character. So, the array size is 9 bytes (i.e., string length 1 byte for null character).
Ex:-
char b[9]="COMPUTER"; // correct
char b[8]="COMPUTER"; // wrong
2. Run Time Initialization
An array can be explicitly initialized at run time. This approach is usually applied for initializing large
arrays.
Ex:- scanf can be used to initialize an array.
Int x[3];
Scanf(“%d%d%d”,&x[0],&x[1],&x[2]);
The above statements will initialize array elements with the values entered through the key board.
(Or)
For(i=0;i<100;i=i+1)
{
If(i<50) Sum[i]=0.0;
Else Sum[i]=1.0;
}
The first 50 elements of the array sum are initialized to 0 while the remaining 50 are initializede to
1.0 at run time.
9. How can we declare and initialize 2D arrays? Explain with examples.
Two-dimensional arrays of fixed length

An array consisting of two subscripts is known as two-dimensional array. These are often known as
array of the array. In two dimensional arrays the array is divided into rows and columns,. These are
well suited to handle the table of data. In 2-D array we can declare an array as :

Declaration:-
Syntax:
Data_type array_name[row_size][column_size] = {{list of first row elements},
{list of second row elements},….
{list of last row elements}};

Ex:- int arr[3][3];

where first index value shows the number of the rows and second index value shows the no. of the
columns in the array. We will learn about the 2-D array in detail in the next section, but now
emphasize more on how these are stored in the memory.
Initialization:-

int arr[3][3] = {{ 1, 2, 3},{4, 5, 6},{7, 8, 9}};

Where first index value shows the number of the rows and second index value shows the no. of the
columns in the array.

10. Explain how two dimensional arrays can be used to represent matrices.
(or)
Define an array and how the memory is allocated for a 2D array?

These are stored in the memory as given below.

· Row-Major order Implementation


· Column-Major order Implementation

In Row-Major Implementation of the arrays, the arrays are stored in the memory in terms of the
row design, i.e. first the first row of the array is stored in the memory then second and so on.
Suppose we have an array named arr having 3 rows and 3 columns then it can be stored in the
memory in the following manner :

int arr[3][3];

arr[0][0] arr[0][1] arr[0][2]

arr[1][0] arr[1][1] arr[1][2]

arr[2][0] arr[2][1] arr[2][2]

Thus an array of 3*3 can be declared as follows :

arr[3][3] = { 1, 2, 3,

4, 5, 6,
7, 8, 9 };

and it will be represented in the memory with row major implementation as follows :
1 2 3 4 5 6 7 8 9

In Column-Major Implementation of the arrays, the arrays are stored in the memory in the term of
the column design, i.e. the first column of the array is stored in the memory then the second and so
on. By taking above eg. we can show it as follows :

arr[3][3] = { 1, 2, 3,

4, 5, 6,

7, 8, 9 };

and it will be represented in the memory with column major implementation as follows :

1 4 7 2 5 8 3 6 9

Two-dimensional arrays of variable length

An array consisting of two subscripts is known as two-dimensional array. These are often known as
array of the array. In two dimensional arrays the array is divided into rows and columns,. These are
well suited to handle the table of data. In 2-D array we can declare an array as :

Declaration:-
Syntax:
Data_type array_name[row_size][column_size];

Initialization :-
int arr[3][3] ;

Where first index value shows the number of the rows and second index value shows the no. of the
columns in the array.
These are stored in the memory as given below.
arr[0][0] arr[0][1] arr[0][2]

arr[1][0] arr[1][1] arr[1][2]

arr[2][0] arr[2][1] arr[2][2]


Ex:-
To initialize values for variable length arrays we can use scanf statement & loop constructs.
for (i=0 ; i<3; i++)
for(j=0;j<3;j++)
scanf(“%d”,&arr[i][j]);
11. Define multi-dimensional arrays? How to declare multi-dimensional arrays?

Multidimensional arrays are often known as array of the arrays. In multidimensional arrays the
array is divided into rows and columns, mainly while considering multidimensional arrays we will
be discussing mainly about two dimensional arrays and a bit about three dimensional arrays.
Syntax:

Data_type arrat_name[size1][size2][size3] - - - - [sizeN];

In 2-D array we can declare an array as :


int arr[3][3] = { 1, 2, 3,

4, 5, 6,

7, 8, 9
};
where first index value shows the number of the rows and second index value shows the no. of the
columns in the array. To access the various elements in 2-D we can access it like this:

printf("%d", a[2][3]);
/* its output will be 6, as a[2][3] means third element of the second row of the array */ In 3-
D we can declare the array in the following manner :
int arr[3][3][3] =

{ 1, 2, 3,
4, 5, 6,
7, 8, 9,

10, 11, 12,


13, 14, 15,
16, 17, 18,

19, 20, 21,


22, 23, 24,
25, 26, 27
};

/* here we have divided array into grid for sake of convenience as in above declaration we have created
3 different grids, each have rows and columns */
If we want to access the element the in 3-D array we can do it as follows :
printf("%d",a[2][2][2]);
/* its output will be 26, as a[2][2][2] means first value in [] corresponds to the grid no. i.e. 3 and
the second value in [] means third row in the corresponding grid and last [] means third column
*/
Ex:-
Int arr[3][5][12];
Float table[5][4][5][3];
Arr is 3D array declared to contain 180 (3*5*12) int type elements. Similarlly tabnle is a 4D
array comntaining 300 elements of float type.
12. Write a program to perform matrix addition.
/*ADDITION OF TWO MATRICES*/
#include<stdio.h> void
main()
{
int i,j;int a[2][2]={1,2,3,4};
int b[2][2]={1,2,3,4};
int c[2][2]; clrscr();
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf("%2d",a[i][j]);
}
printf("\n\n");
}
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{printf("%d",b[i][j]);
}
printf("\n\n");
}
Printf(“\n The addition of given two matrices is\n”);
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
Printf(“%d”,c[i][j]);
getch();
}

OUTPUT:

1 2
3 4

1 2
3 4
The addition of given two matrices is
2 4
6 8
13. Write a program to perform matrix multiplication

/*MATRIX MULTIPLICATION*/
#include<stdio.h>
#include<conio.h>

void main()
{
int a[3][3],b[3][3],c[3][3],i,j,k;
clrscr();
printf("\n enter the matrix elements");
for(i=0;i<3;i++);
{
for(j=0;j<3;j++);
{
scanf("%d",&a[i][j]);
}
}
printf("\n a matrix is\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d\t",&b[i][j]);
}
}
printf("\n b matrix is\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t",b[i][j]);
}
printf("\n");
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{ c[i][j]=0;
for(k=0;k<3;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
}
printf("\n The multiplication of given two matrices is\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t",c[i][j]);
}
printf("\n");
}
getch();
}
OUTPUT:
enter the matrix elements

1 1 1
1 1 1
1 1 1

22 2
22 2
22 2
A matrix is:
1 1 1

1 1 1

1 1 1

B matrix is:

2 2 2

2 2 2
2 2 2

The multiplication of given two matrices is


6 6 6
6 6 6
6 6 6
14. Write program to find largest of the given 3 integer numbers.
Refer QNO 1 if-else statement ex program

15. Define C string? How to declare and initialize C strings with an example?
C Strings:-
In C language a string is group of characters (or) array of characters, which is terminated by
delimiter \0 (null). Thus, C uses variable-length delimited strings in programs.
Declaring Strings:-
Since strings are group of characters, generally we use the structure to store these characters is a
character array.
Syntax:- char string_name[size];
The size determines the number of characters in the string name.
Ex:- char city[10];
Char name[30];
Initializing strings:-
There are several methods to initialize values for string variables.

Ex:- char city[8]=”NEWYORK”;


Char city[8]={‘N’,’E’,’W’,’Y’,’O’,’R’,’K’,’\0’};
The string city size is 8 but it contains 7 characters and one character space is for NULL
terminator.
Storing strings in memory:-
In C a string is stored in an array of characters and terminated by \0 (null).

A string is stored in array, the name of the string is a pointer to the beginning of the string. The
character requires only one memory location.
If we use one-character string it requires two locations. The difference shown below,

The difference between array & string shown below,

Because strings are variable-length structure, we must provide enough room for maximum- length
string to store and one byte for delimiter.

Why do we need null?


A string is not a datatype but a data structure. String implementation is logical not physical. String
implementation is logical not physical. The physical structure is array in which the string is stored.
The string is variable-length, so we need to identify logical end of data in that physical structure.
String constant (or) Literal:-
String constant is a sequence of characters enclosed in double quotes. When string constants are used
in C program, it automatically initializes a null at end of string.
Ex:- “Hello” “Welcome” “Welcome to C Lab”

16. Explain about the string Input/ Output functions with example?
Reading and Writing strings:-
C language provides several string functions for input and output.
String Input/Output Functions:-
C provides two basic methods to read and write strings. Using formatted input/output functions and
using a special set of string only functions.
Reading strings from terminal:-
(a) Using formatted input/output:- scanf can be used with %s format specification to read a string.
Ex:- char name[10];
scanf(“%s”,name);
Here don’t use ‘&’ because name of string is a pointer to array. The problem with scanf, %s is that it
terminates when input consisting of blank space between them.
Ex:- NEW YORK
Reads only NEW (from above example).
(b) Special set of functions:-
(1) getchar():- It is used to read a single character from keyboard. Using this function repeatedly we
may read entire line of text and stored in memory.
Ex:- char ch=’z’;
ch=getchar();
(2) gets():- It is more convenient method of reading a string of text including blank spaces.
Ex:- char line[100];
gets(line);
Writing strings on to the screen:-
(1) Using formatted output functions:- printf with %s format specifier we can print strings in
different formats on to screen.
Ex:- char name[10];
printf(“%s”,name);
Ex:- char name[10];

printf(“%0.4”,name);
/* If name is JANUARY prints only 4 characters ie., JANU */

Printf(“%10.4s”,name);

printf(“%-10.4s”,name);
(2) Using special set of functions:-
(a) putchar():- It is used to print one by one character.
Ex:- putchar(ch);
(b) puts():- It is used to print strings including blank spaces.
Ex:- char line[15]=”Welcome to lab”;
puts(line);
17. Explain about the following string handling functions with example programs.
(i) strlen ( ) (ii) strcpy (iii) strcmp ( ) (iv) strcat
(i) strlen( )
C supports a number of string handling functions. All of these built-in functions are aimed at
performing various operations on strings. All of these built-in functions are defined in the header file
string.h.
strlen() function: This function is used to find the length of the string excluding the NULL
character. In other words, this function is used to count the number of characters in a string. Its
syntax is as follows:

intstrlen(string);

Example: char str1[ ] = “WELCOME”;


int n;
n = strlen(str1);
/* A program to calculate length of string by using strlen() function*/
#include<stdio.h>
#include<string.h>
main()
{
char string1[50];
int length;
printf(“\n Enter any string:”);
gets(string1);
length=strlen(string1);
printf(“\n The length of string=%d”,length);
}
(ii) strcpy( )
This function is used to copy one string to the other. Its syntax is as follows:

strcpy(string1,string2);

where string1 and string2 are one-dimensional character arrays.


This function copies the content of string2 to string1. E.g., string1 contains master and
string2 contains madam, then string1 holds madam after execution of the strcpy (string1,string2)
function.
Example: char str1[ ] = “WELCOME”;
char str2[ ] =”HELLO”;
strcpy(str1,str2);
/* A program to copy one string to another using strcpy() function */
#include<stdio.h>
#include<string.h>
main( )
{
char string1[30],string2[30];
printf(“\n Enter first string:”);
gets(string1);
printf(“\n Enter second string:”);
gets(string2);
strcpy(string1,string2);
printf(“\n First string=%s”,string1);
printf(“\n Second string=%s”,string2);
}
(iii) strcmp ( )
This function compares two strings character by character (ASCII comparison) and returns one of
three values {-1,0,1}. The numeric difference is ‘0’ strings are equal otherwise if it is negative
string1 is alphabeticallly above string2 or if it is positive string2 is alphabeticallly above string1.
Its syntax is as follows:

intstrcmp(string1,string2);

Example: char str1[ ] = “ROM”;


char str2[ ] =”RAM”;
strcmp(str1,str2);
(or) strcmp(“ROM”,”RAM”);
/* A program to compare two strings using strcmp() function */

#include<stdio.h>
#include<string.h>
main()
{
char string1[30],string2[15];
int x;
printf(“\n Enter first string:”);
gets(string1);
printf(“\n Enter second string:”);
gets(string2);
x=strcmp(string1,string2);
if(x==0)
printf(“\n Both strings are equal”);
else if(x>0)
printf(“\n First string is bigger”);
else
printf(“\n Second string is bigger”);
}
(iv) strcat ( )
This function is used to concatenate two strings. i.e., it appends one string at the end of the
specified string. Its syntax as follows:

strcat(string1,string2);

where string1 and string2 are one-dimensional character arrays.


This function joins two strings together. In other words, it adds the string2 to string1 and the
string1 contains the final concatenated string. E.g., string1 contains prog and string2 contains ram,
then string1 holds program after execution of the strcat() function.
Example: char str1[10 ] = “VERY”;
char str2[ 5] =”GOOD”;
strcat(str1,str2);
/* A program to concatenate one string with another using strcat() function*/

#include<stdio.h>
#include<string.h>
main()
{
char string1[30],string2[15];
printf(“\n Enter first string:”);
gets(string1);
printf(“\n Enter second string:”);
gets(string2);
strcat(string1,string2);
printf(“\n Concatenated string=%s”,string1);
}
18. Write about storage representation of fixed and variable length format strings with
example?
String concepts:-
In general a string is a series of characters (or) a group of characters. While implementation of
strings, a string created in pascal differs from a string created in C language.

1. Fixed-length strings:
When implementing fixed-length strings, the size of the variable is fixed. If we make it too small we
can’t store, if we make it too big, then waste of memory. And another problem is we can’t
differentiate data (characters) from non-data (spaces, null etc).
2. Variable-length string:
The solution is creating strings in variable size; so that it can expand and contract to accommodate
data. Two common techniques used,
(a) Length controlled strings:
These strings added a count which specifies the number of characters in the string.
Ex:-

5 H E L L O

(b) Delimited strings:


Another technique is using a delimiter at the end of strings. The most common delimiter is the
ASCII null character (\0).

Ex:-

19. How can we declare and initialize Array of strings in C? Write a program to read
and display array of strings.
We have array of integers, array of floating point numbers, etc.. similarly we have array of
strings also.
Collection of strings is represented using array of strings.
Declaration:-
char arr[row][col];
where,
arr - name of the array
row - represents number of strings
col - represents size of each string

Initialization:-
char arr[row][col] = { list of strings };
Example:-
char city[5][10] = { “DELHI”, “CHENNAI”, “BANGALORE”, “HYDERABAD”,
“MUMBAI” };

D E L H I \0
C H E N N A I \0
B A N G A L O R E \0

H Y D E R A B A D \0

M U M B A I \0

In the above storage representation memory is wasted due to the fixed length for all strings. More
convenient way to initialize array of strings is as follows.
char *city[5] = { “DELHI”, “CHENNAI”, “BANGALORE”, “HYDERABAD”,
“MUMBAI” };

D E L H I \0

C H E N N A I \0

B A N G A L O R E \0

H Y D E R A B A D \0

M U M B A I \0

Program to read and display array of strings


# include<stdio.h>
#include<conio.h>
void main( )
{
char *city[5];
int i;
clrscr( );
printf(“enter 5 city names:”);
for( i=0; i<5; i++)
scanf(“%s”,city[i]);
for( i=0; i<5; i++)
printf(“city[%d] = %s”,i,city[i]);
getch( );
}
Output:-

Enter 5 city names: Hyderabad Mumbai Chennai Bangalore Delhi


City[0] = Hyderabad
City[1] = Mumbai
City[2] = Chennai
City[3] = Bangalore
City[4] = Delhi
20. Write the syntax and representations for the conversion of String to Data.

String to Data Conversion


The string scan function is called sscanf. This function scans a string as though the data were coming
from a file.
sscanf

String Variables

The function declaration is as follows:

Syntax:- int sscanf(char* str, “format string”, variables);

where,
str - the string contains the data to be scanned. The string may be read from file or using gets function.
format string – format specifiers such as %d, %c, %f etc.
variables – list of variables in which the data will be converted

sscanf is a one-to-many function. It splits one string into many variables.

Ex: program for conversion of string to data.


#include<stdio.h> void
main( )
{
char str[ ]= “ RAMU 985 98.5”;
char name[10]; int
tot_marks;
float avg;
sscanf(str,”%s%d%f”,name,&tot_marks,&avg);
printf(“Name=%s\n”,name);
printf(“Total marks=%d\n”,tot_marks);
printf(“Average=avr%f\n”,avg);
getch( );
}
Output:
Name = RAMU Total
marks = 985 Average =
98.5
Unit-3

Functions: Introduction – using functions – Function declaration/ prototype – Function definition


– function call – return statement – Passing parameters – Scope of variables – Storage Classes –
Recursive functions.

3.1 : Introduction: Functions are a group of statements that have been given a name. This allows you to break
your program down into manageable pieces and reuse your code.
🞂​ The advantages of functions are:
◦ Function makes the lengthy and complex program easy and in short forms. It means large
program can be sub-divided into self-contained and convenient small modules having unique
name.
◦ The length of source program can be reduced by using function by using it at different places in
the program according to the user’s requirement.
◦ By using function, memory space can be properly utilized. Also less memory is required to run
program if function is used.
◦ They also allow more than one person to work on one program.
◦ Function increases the execution speed of the program and makes the programming
simple.
◦ By using the function, portability of the program is very easy.
◦ It removes the redundancy (occurrence of duplication of programs) i.e. avoids the repetition and
saves the time and space.
◦ Debugging (removing error) becomes very easier and fast using the function sub-programming.
◦ Functions are more flexible than library functions.
◦ Testing (verification and validation) is very easy by using functions.
◦ User can build a customized library of different functions used in daily routine having specific
goal and link with the main program similar to the library functions.
The functions are classified into standard functions and user-defined functions. The standard functions
are also called library functions or built in functions. All standard functions, such as sqrt(), abs(), log(), sin(),
pow() etc. are provided in the library of functions. These are selective.
Most of the applications need other functions than those available in the software. These functions
must be written by the user (programmer), hence, the name user-defined functions.
You can write as many functions as you like in a program as long as there is only one main ().
As long as these functions are saved in the same file, you do not need to include a header file.
They will be found automatically by the compiler.
There are 3 parts for using functions:
Declaring them (prototypes).
Calling them,
Defining them and
3.2 Function Declaration (Prototype):
Function declaration means specifying the function as a variable depending on the return value.
It is declared in the declaration part of the main program. The
default return value from a function is always an integer.
If the function is returning a value other than an integer, it must be declared with the data type of the
value it returns.
The general form of function declaration in ANSI form is as follows:
Type_of_return_value function_name (parameter types);

3.3 Function Definition :


Defining a function means writing an actual code for the function which does a specific and
identifiable task.
The general form of a ANSI method of function definition is as follows:
type_specifier function_name (formal parameters)
{
variable declaration; /* with in the function */
body of function;
*
*
return (value_computed);
}
type_specifier specifies the type of value that the function's return statement returns. If nothing is
returned to the calling function, then data type is void.
function_name is a user-defined function name. It must be a valid C identifier.
formal parameters is the type declaration of the variables of parameter list.
return is a keyword used to send the output of the function, back to the calling function.
{ is the beginning of the function.

} is the end of function.


All the statements placed between the left brace and the corresponding right brace
constitute the body of a function.
3.4 Calling functions:
 When you wish to use a function, you can "call" it by name.
 Control is sent to the block of code with that name.
 Any values that the function needs to perform its job are listed in the parentheses that immediately
follow the name are called arguments.
 The computer will retrieve the values held by the variables and hand them off to the function for its use.
 The number of arguments (or values) must match the variables in the definition by type and number.
 A semicolon must be present, when the function is called within the main() function.
 The general form of a ANSI method of function call is as follows:
o function_name (actual parameters);

3.5 return statement

The return causes an immediate exit from a function to the point from where the function is called.
It may also be used to return one value per call. All functions, except those of type void, return a
value. If no return statement is present, most compilers will cause a 0 to be returned. The return
statement can be any one of the types as shown below:

1. return;
2. return ();
3. return (constant);
4. return (variable);
5. return (expression);
6. return (conditional expression);
7. return (function);

The first and second return statements, does not return any value and are just equal to the closing
brace the function. If the function reaches the end without using a return statement, the control is
simply transferred back to the calling portion of the program without returning any value. The
presence of empty return statement is recommended in such situations.

The third return statement returns a constant function. For example:

if (x <= 10)
return (1);

The fourth return statement returns a variable to the calling function. For example:

if (x <= 10)
return (x);

The fifth return statement returns a value depending upon the expression specified inside the
parenthesis. For example:

return (a + b * c);

The sixth return statement returns a value depending upon the result of the conditional
expression specified inside the parenthesis. For example:

return (a > b ? 1 : 2);


The last return statement calls the function specified inside the parenthesis and collects the result
obtained from that function and returns it to the calling function. For example:

return (pow (4, 2));

The parenthesis used around the expression or value used in a return statement is optional.

3.6 Passing parameters

Arguments and parameters are the variables used in a program and a function. Variables used in the
calling function are called arguments. These are written within the parentheses followed by the name
of the function. They are also called actual parameters, as they are accepted in the main program (or
calling function).

Variables used in the function definition (called function) are called parameters. They are also
referred to as formal parameters, because they are not the accepted values. They receive values from
the calling function. Parameters must be written within the parentheses followed by the name of the
function, in the function definition.

Parameter passing mechanisms:


A method of information interchange between the calling function and called function is known as
parameter passing. There are two methods of parameter passing:
1. Call by value
2. Call by reference

3.6.1. Call by Value:


The call-by-value method copies the value of an argument into the formal parameter of the function.
Therefore, changes made by the function to the parameters have no effect on the variables used to
call it.

Example:

# include <stdio.h>
void swap (int x, int y); /* function prototype */ main
()
{
int x, y; x
= 10;
y = 20;
swap (x, y); /* values passed */
}

void swap (int a, int b) /* function definition */


{
int temp;

temp = a;
a = b;
b = temp;
printf (“%d %d\n”, a, b);
}
3.6.2. Call by Reference:
The call by reference method copies the address of an argument into the formal parameter. Inside the
function, this address is used to access the argument used in the call. In this way, changes made to
the parameter affect the variable used in the call to the function.

Call by reference is achieved by passing a pointer as the argument. Of course, in this case, the
parameters must be declared as pointer types. The following program demonstrates this:

Example:

# include <stdio.h>
void swap (int *x, int *y); /* function prototype */ main
()
{
int x, y; x
= 10;
y = 20;
swap (&x, &y); /* addresses passed */ printf
(“%d %d\n”, x, y);
}
void swap (int *a, int *b)
{
int temp; temp =
*a;
*a = *b;
*b = temp;
}
The differences between call by value and call by reference:

Call by value Call by reference

int a; int a;

Formal parameter ‘a’ is a local variable. Formal parameter is ‘a’ local reference.

It cannot change the actual parameter. It can change the actual parameter.

Actual parameter may be a constant, a variable, or an


expression. Actual parameter must be a variable.

3.7 Types of functions

We have some other type of functions where the arguments and return value may be present or
absent. Such functions can be categorized into:

1. Functions with no arguments and no return value.


2. Functions with arguments and no return value.
3. Functions with no arguments but return value.
4. Functions with arguments and return value.

Functions with no arguments and no return value:


Here, the called function does not receive any data from the calling function and, it does not return
any data back to the calling function. Hence, there is no data transfer between the calling function
and the called function.
Example:
This program illustrates the function with no arguments and no return value.

# include <stdio.h> void


read_name (); main ()
{
read_name ();
}
void read_value () /*no return value */
{
char name [10];
printf (“Enter your name: ”);
scanf (“%s”, name);
printf (“\nYour name is %s: ”, name);
}
Output:

Enter your name: Herbert


Your name is: Herbert
Functions with arguments and no return value:
Here, the called function receives the data from the calling function. The arguments and parameters
should match in number, data type and order. But, the called function does not return and value back
to the calling function. Instead, it prints the data in its scope only. It is one-way data communication
between the calling function and the called function.
Example:
This program illustrates the function with arguments but has no return value.

#include <stdio.h> void


maximum (x, y); main()
{
int x, y;
printf (“Enter the values of x and y: ”);
scanf (“%d %d”, &x, &y);
maximum (x, y);
}
void maximum (int p, int q) /* function to compute the maximum */
{
if (p > q)
printf (“\n maximum = %d”, p);
else
printf (“\n maximum = %d” q);
return;
}
Output:
Enter the values of x and y: 14 10
maximum = 14
Function with no arguments but return value:
Here, the called function does not receive any data from the calling function. It manages with
its local data to carry out the specified task. However, after the specified processing the called
function returns the computed data to the calling function. It is also a one-way data
communication between the calling function and the called function.

Example:
This program illustrates the function with no arguments but has a return value.

#include <stdio.h>
float total ();
main ()
{
float sum;
sum =
total ();
printf (“Sum = %f\n”, sum);
}
float total ()
{
float x, y;
x = 20.0;
y = 10.0;
return (x + y);
}
Output:
Sum = 30.000000
Function with arguments and return value:
When a function has arguments it receives data from the calling function and does some
process and then returns the result to the called function. In this way the main() function will
have control over the function.

Example:
/* program to find the sum of first N natural numbers */
#include <stdio.h>
int sum (int x); /* function
prototype*/ void main ()
{
int n;
printf (“Enter the limit: ”);
scanf (“%d”, &n);
printf (“sum of first %d natural numbers is: %d”, n, sum(n));
}
int sum(int x)
{
int i, result = 0
for (i=1; i <= x; i++)
result += i;
return (result);
}

Output:

Enter the limit: 5


Sum of first 5 natural numbers is: 15

The main() is the calling function which calls the function sum(). The function sum() receives
a single argument. Note that the called function (i.e., sum ()) receives its data from the calling
function (i.e., main()). The return statement is employed in this function to return the sum of
the n natural numbers entered from the standard input device and the result is displayed from
the main() function to the standard output device. Note that int is used before the function name
sum() instead of void since it returns the value of type int to the called function.

Important points to be noted while calling a function:


· Parenthesis are compulsory after the function name.
· The function name in the function call and the function definition must be same.
· The type, number, and sequence of actual and formal arguments must be same.
· semicolon must be used at the end of the statement when a function is called.
· The number of arguments should be equal to the number of parameters.
· There must be one-to-one mapping between arguments and parameters. i.e. they should be in
the same order and should have same data type.
· Same variables can be used as arguments and parameters.
· The data types of the parameters must match or be closely compatible. It is very risky to call a
function using an actual parameter that is floating point data if the formal parameter was
declared as an integer data type. You can pass a float to a double, but should not do the
opposite. You can also pass a short int to an int, etc. But you should not pass any type of integer
to any type of floating point data or do the opposite.

Nested Functions:
We have seen programs using functions called only from the main() function. But there are
situations, where functions other than main() can call any other function(s) used in the
program. This process is referred as nested functions.
Example:
#include <stdio.h>
void func1();
void func2();
void main()
{
printf (“\n Inside main function”);
func1();
printf (“\n Again inside main function”);
}
void func1()
{
printf (“\n Inside function
1”); func2();
printf (“\n Again inside function 1”);
}
void func2()
{
printf (“\n Inside function 2”);
}
Output:
Inside main function
Inside function 1
Inside function 2
Again inside
function 1
Again inside main function

Uses two functions func1() and func2() other than the main() function. The main() function
calls the function func1() and the function func1() calls the function func2().

3.8 Scope of variables


 A scope is a region of the program, and the scope of variables refers to the area of the program where
the variables can be accessed after its declaration.
 In C every variable defined in scope.
 In C programming, variable declared within a function is different from a variable declared
outside of
 a function.
The variable can be declared in three places. These are:

Position Type

Inside a function or a block. local variables

Out of all functions. Global variables

In the function parameters. Formal parameters

Local Variables
🞂​ Variables that are declared within the function block and can be used only within the
function is called local variables.
🞂​ Local scope or block scope
◦ A local scope or block is collective program statements put in and declared within a
function or block (a specific region enclosed with curly braces) and variables lying
inside such blocks are termed as local variables.
◦ All these locally scoped statements are written and enclosed within left ({) and right
braces (}) curly braces.
◦ There's a provision for nested blocks also in C which means there can be a block or a
function within another block or function.
◦ So it can be said that variable(s) that are declared within a block can be accessed within that
specific block and all other inner blocks of that block, but those variables cannot be
accessed outside the block.
#include
<stdio.h> int
main ()
{
/* local variable definition and
initialization */ int x,y,z;
/* actual
initialization */ x =
20;
y = 30;
z = x + y;
printf("value of x = %d,y = %d and z = %d\n", x, y,
z); return 0;
}

Global variables
🞂​ Variables that are declared outside of a function block and can be accessed inside the
function is called global variables.
🞂​ Global scope
◦ Global variables are defined outside a function or any specific block, in most of the case,
on the top of the C program.
◦ These variables hold their values all through the end of the program and are accessible
within any of the functions defined in your program.
◦ Any function can access variables defined within the global scope, i.e., its availability
stays for the entire program after being declared.
include <stdio.h>
/* global variable
definition */ int z;
int main ()
{
/* local variable definition and
initialization */ int x,y;
/* actual
initialization */ x =
20;
y = 30;
z = x + y;
printf ("value of x = %d, y = %d and z = %d\n", x, y,
z); return 0;
}
🞂​ A program can have same name for local and global variables but the value of
local variable inside a function will take preference. Here is an example −

#include <stdio.h>
/* global variable
declaration */ int g = 20;
int main ()
{ /* local variable
declaration */ int g = 10;
printf ("value of g
= %d\n", g); return 0;
}
When the above code is compiled and executed, it produces the following result −

value of g = 10

Formal Parameters
Formal parameters, are treated as local variables with-in a function and they take
precedence over global variables. Following is an example –

#include <stdio.h>
Int a=20; /* global variable
declaration */ int main ()
{ /* local variable declaration in main
function */ int a = 10; b=20;c=0;
printf ("value of a in main()
= %d\n", a); c = sum( a, b);
printf ("value of c in main()
= %d\n", c); return 0;
}
/* function to add two
integers */ int sum(int a, int
b)
{
printf ("value of a in sum()
= %d\n", a); printf ("value of b in
sum() = %d\n", b); return a + b;
When the above code is compiled and executed, it produces the following
result − value of a in main() = 10
value of a in
sum() = 10 value
of b in sum() = 20
value of c in
main() = 30
🞂​ When a local variable is defined, it is not initialized by the system, you must
initialize it yourself. Global variables are initialized automatically by the system
when you define them as follows −

Data Type Initial Default Value

int 0

char '\0'

float 0

double 0

pointer NULL
It is a good programming practice to initialize variables properly, otherwise your
program may produce unexpected results, because uninitialized variables will take
some garbage value already available at their memory location.
3.9 Storage Classes
Storage classes are used to define the scope (visibility) and life-time of variables and/or
functions. Every variable and function in C has two attributes: type and storage class. There are
four storage classes:

· auto
· static
· extern or global and
· register
The auto storage class:
Variables declared within function bodies are automatic by default. If a compound statement
starts with variable declarations, then these variables can be acted on within the scope of the
enclosing compound statement. A compound statement with declarations is called a block to
distinguish it from one that does not begin with declarations.
Declarations of variables within blocks are implicitly of storage class automatic. The key- word
auto can be used to explicitly specify the storage class. An example is:

auto int a, b, c;
auto float f;
Because the storage class is auto by default, the key-word auto is seldom used.

When a block is entered, the system allocates memory for the automatic variables. With in that
block, these variables are defined and are considered “local” to the block. When the block is
exited, the system releases the memory that was set aside for the automatic variables. Thus, the
values of these variables are lost. If the block is reentered, the system once again allocates
memory, but previous values are unknown. The body of a function.

definition constitutes a block if it contains declarations. If it does, then each invocation of the
function set up a new environment.

The static storage class:


It allows a local variable to retain its previous value when the block is reentered. This is in
contrast to automatic variables, which lose their value upon block exit and must be
reinitialized. The static variables hold their values throughout the execution of the program. As
an example of the value-retention use of static, the outline of a function that behaves differently
depending on how many times it has been called is:

void fun (void)


{
static int cnt = 0
++ cnt;
if (cnt % 2 == 0)
... /* do something */
else
... /* do something different */
}
The first time the function is invoked, the variable cnt is initialized to zero. On function exit,
the value of cnt is preserved in memory. Whenever the function is invoked again, cnt is not
reinitialized. Instead, it retains its previous value from the last time the function was called. The
declaration of cnt as a static int inside of fun () keeps it private of fun (). If it was declared
outside of the function, then other functions could access it, too.

Static variables are classified into two types.

1. internal static variables


2. external static variables
External static variables are declared outside of all functions including the main() function.
They are global variables but are declared with the keyword static. The external static variables
cannot be used across multi-file program.
A static variable is stored at a fixed memory location in the computer, and is created and
initialised once when the program is first started. Such a variable maintains its value between
calls to the block (a function, or compound statement) in which it is defined. When a static
variable is not initialized, it takes a value of zero.
The storage class extern:

One method of transmitting information across blocks and functions is to use external
variables. When a variable is declared outside a function, storage is permanently assigned to it,
and its storage class is extern. Such a variable is considered to be global to all functions
declared after it, and upon exit from the block or function, the external variable remains in
existence. The following program illustrates this:

# include <stdio.h>
int a = 1, b = 2, c = 3; /* global variable*/
int fun (void); /* function
prototype*/ int main (void)
{
printf (“%3d\n”, fun ()); /* 12 is printed */
printf (“%3d%3d%3d\n”, a, b, c); /* 4 2 3 is
printed */}
int fun (void)
{
int b, c;
a = b = c = 4; /* b and c are local */
return (a + b + c); /* global b, c are masked*/
}
Note that we could have written:

extern int a = 1, b = 2, c = 3;

The extern variables cannot be initialised in other functions whereas we can use for assignment.

This use of extern will cause some traditional C compilers to complain. In ANSI C, this use is
allowed but not required. Variables defined outside a function have external storage class, even
if the keyword extern is not used. Such variables cannot have auto or register storage class.

The keyword extern is used to tell the compiler to “look for it else where, either in this file or
in some other file”. Let us rewrite the last program to illustrate a typical use of the keyword
extern:
In file file1.c
#include <stdio.h>
# include “file2.c”
int a=1, b=2, c=3; /* external
variable */ int fun (void)
int main (void)
{
printf (“The values of a, b and c are: %3d%3d%3d\n”, a, b, c);
printf (“The sum of a + b + c is: %3d\n”, fun ());
printf (“The values of a, b and c are: %3d%3d%3d\n”, a, b, c);
return 0;
}
In file file2.c
int fun (void)
{
extern int a; /* look for it
elsewhere */ int b, c;
a = b = c = 4;
return (a + b +
c);
}
Output:
The values of a, b and c are: 1 2 3 The sum of a + b + c is: 12
The values of a, b and c are: 4 2 3
The two files can be compiled separately. The use of extern in the second file tells the compiler
that the variable a will be defined elsewhere, either in this file or in some other. The ability to
compile files separately is important when writing large programs.

External variables never disappear. Because they exist throughout the execution life of the
program, they can be used to transmit values across functions. They may, however, be hidden if
the identifier is redefined.
ormation can be passed into a function two ways; by use of external variable and by use of the
parameter passing mechanism. The use of the parameter mechanism is the best preferred
method. Don't overuse ‘extern’ variables. It is usually better to pass lots of arguments to
functions rather than to rely on hidden variables being passed (since you end up with clearer
code and reusuable functions).

The register storage class:


This is like `auto' except that it asks the compiler to store the variable in one of the CPU's fast
internal registers. In practice, it is usually best not to use the `register' type since compilers are
now so smart that they can do a better job of deciding which variables to place in fast storage
than you can.
The use of storage class register is an attempt to improve execution speed. When speed is a
concern, the programmer may choose a few variables that are most frequently accessed and
declare them to be of storage class register. Common candidates for such treatment include
loop variables and function parameters. The keyword register is used to declare these variables.

Examples:
1) register int x;
2) register int counter;
The declaration register i; is equivalent to register int i;

Storage Storage Default Value Scope Lifetime


Classes Place

auto RAM Garbage Value Local Within function

extern RAM Zero Global Till the end of the main program
Maybe declared anywhere in the
program

static RAM Zero Local Till the end of the main program,
Retains value between multiple
functions call

register Register Garbage Value Local Within the function

3.10 Recursive functions

Recursion in C language is basically the process that describes the action when a function calls
a copy of itself in order to work on a smaller problem. Recursive functions are the function that
calls themselves and this type of function calls are known as recursive calls. The recursion in C
generally involves various numbers of recursive calls. It is considered to be very important to
impose a termination condition of recursion. Recursion code in the C language is generally
shorter than the iterative code and it is known to be difficult to understand.
ursion cannot be applied to all the problem, but Recursion in C language is very useful for the
tasks that can be generally be defined in terms of similar subtasks but it cannot be applied to all
the problems. For instance: recursion in C can be applied to sorting, searching, and traversal
problems.

As function call is always overhead, iterative solutions are more efficient than recursion. Any of
the problems that can generally be solved recursively; it can be also solved iteratively. Apart
from these facts, there are some problems that are best suited to only be solved by the recursion
for instance: tower of Hanoi, factorial finding, Fibonacci series, etc.

What is Recursive Function?


The working of a recursive function involves the tasks by dividing them generally into the
subtasks. Some specific subtask have a termination condition defined that has to be satisfied
by them. In the next step, the recursion in C stops and the final result is derived from the
function.

The base case is the case at which the function doesn’t recur in C and there are instances
where the function keeps calling itself in order to perform a subtask and that is known as the
recursive case.

Recursive functions are two types:


1. Direct Recursion
2. In Direct Recursion

Direct Recursion: if a function calls itself then it is direct recursion.

Exampl
e:
void
main(
)
{

main();
}

Indirect recursion: If a function calls another function and if that function calls it self. Then
it is indirect recursion.

Exampl
e:
Void
main()
{
--
--
Print();
--
--
}
Void Print()
{
--
--
Print();--
} Check:Output:0 12 3 4567 89
Example:
#include <stdio.h>
void printnum ( int begin )
{
printf( "%d", begin );
if ( begin < 9 ) /* The base case is when begin is no longer */
{ /* less than 9 */
printnum ( begin + 1 );
}
/* display begin again after we've already printed everything from 1 to 9
* and from 9 to begin + 1
*/ printf( "%d", begin );
}

int main()
{
printnum
(0);
getchar()
;
}

Pointer Introduction:-

One of the powerful features of C is ability to access the memoryvariables by


their memory address.
This can be done by using Pointers. The real power of C lies in the properuse of
Pointers.
A pointer is a variable that can store an address of a variable (i.e., 112300).We say
that a pointer points to a variable that is stored at thataddress.
A pointer itself usually occupies 4 bytes of memory (then it can addresscells from 0
to 232-1).

Advantages of Pointers:-
1. A pointer enables us to access a variable that is defined out side the function.
2. Pointers are more efficient in handling the data tables.
3. Pointers reduce the length and complexity of a program.
4. They increase the execution speed.
Definition :-
A variable that holds a physical memory address is called a pointer variable or Pointer
Declaration :Datatype * Variable-name;

Eg:- int *ad; /* pointer to int */


char *s; /* pointer to char */
float *fp; /* pointer to float
*/

char **s; /* pointer to variable that is a pointer to char */

Dangling Pointers in C
The most common bugs related to pointers and memory management is dangling/wild pointers.
Sometimes the programmer fails to initialize the pointer with a valid address, then this type of
initialized pointer is known as a dangling pointer in C.

Dangling pointer occurs at the time of the object destruction when the object is deleted or de-
allocated from memory without modifying the value of the pointer. In this case, the pointer is
pointing to the memory, which is de-allocated. The dangling pointer can point to the memory,
which contains either the program code or the code of the operating system. If we assign the value
to this pointer, then it overwrites the value of the program code or operating system instructions;
in such cases, the program will show the undesirable result or may even crash. If the memory is
re-allocated to some other process, then we dereference the dangling pointer will cause the
segmentation faults.
Let's understand the dangling pointer through some C programs. Using
free() function to de-allocate the memory.
1. #include <stdio.h>
2. int main()

3. {

4. int *ptr=(int *)malloc(sizeof(int));

5. int a=560;

6. ptr=&a;

7. free(ptr);

8. return 0;

9. }
In the above code, we have created two variables, i.e., *ptr and a where 'ptr' is a pointer and 'a' is a
integer variable. The *ptr is a pointer variable which is created with the help of malloc()
function. As we know that malloc() function returns void, so we use int * to convert void pointer into
int pointer.

The statement int *ptr=(int *)malloc(sizeof(int)); will allocate the memory with 4 bytes shown
in the below image:

The statement free(ptr) de-allocates the memory as shown in the below image with a cross sign,
and 'ptr' pointer becomes dangling as it is pointing to the de-allocated memory.

If we assign the NULL value to the 'ptr', then 'ptr' will not point to the deleted memory. Therefore,
we can say that ptr is not a dangling pointer, as shown in the below image:
Variable goes out of the scope

When the variable goes out of the scope then the pointer pointing to the variable becomes a
dangling pointer.
· A pointer is a variable that contains an address which is a location ofanother
variable in memory.

Consider the Statement


p=&i;

Here &‟ is called address of a variable. ‘p’


contains the address of a variable i.

The operator & returns the memory address of variable on which it isoperated, this is
called Referencing.
The * operator is called an indirection operator or dereferencing operatorwhich is used to
display the contents of the Pointer Variable.

Consider the following Statements :int


*p,x; x
=5;
p= &x;
Assume that x is stored at the memory address 2000. Then the output for thefollowing printf
statements is :
Output

Printf(“The Value of x is %d”,x); 5


Printf(“The Address of x is %u”,&x); 2000

Printf(“The Address of x is %u”,p); 2000

Printf(“The Value of x is %d”,*p); 5

Printf(“The Value of x is %d”,*(&x)); 5

Pointers to pointers:-
A pointer to a pointer is a form of multiple indirection, or a chain ofpointers.
Normally, a pointer contains the address of a variable.
When we define a pointer to a pointer, the first pointer contains the address of the
second pointer, which points to the location that containsthe actual value as shown below.
· A variable that is a pointer to a pointer must be declared assuch.
· This is done by placing an additional asterisk in front of itsname. For
example, the following declaration declares a pointer to a pointer of type
int –

int **var;
Arrays:-
An array is defined as the collection of similar type of dataitems stored at contiguous
memory locations.
Arrays are the derived data type in C programming language which can store the
primitive type of data suchas int, char, double, float, etc.
It also has the capability to store the collection of deriveddata types, such as
pointers, structure, etc.
The array is the simplest data structure where each dataelement can be randomly
accessed by using its index number.
Pointer Arithmetic in C:-

Pointer Arithmetic in C

We can perform arithmetic operations on the pointers likeaddition, subtraction, etc.


However, as we know that pointer contains the address,the result of an arithmetic
operation performed on the
pointer will also be a pointer if the other operand is oftype integer.
In pointer-from-pointer subtraction, the result will be aninteger value.
Following arithmetic operations are possible on thepointer in C language:

o Increment
o Decrement
o Addition
o Subtraction
o Comparison

Incrementing Pointer in C:-


If we increment a pointer by 1, the pointer will startpointing to the immediate
next location.
This is somewhat different from the general arithmetic since the value of the pointer
will get increased by the sizeof the data type to which the pointer is pointing.
The Rule to increment the pointer is given below:

new_address= current_address + i * size_of(data type)

Where i is the number by which the pointer get increased.

Decrementing Pointer in C

Like increment, we can decrement a pointer variable. Ifwe decrement a pointer, it


will start pointing to the previous location.

The formula of decrementing the pointer is given below:


new_address= current_address - i * size_of(data type)

C Pointer Addition

We can add a value to the pointer variable. The formula ofadding value to pointer is given
below:
new_address= current_address + (number * size_of(data type))
Pointer Subtraction

Like pointer addition, we can subtract a value from the pointer variable. Subtracting any
number from a pointer willgive an address. The formula of subtracting value from the
pointer variable is given below:
new_address= current_address - (number * size_of(data type))

Memory Allocation Function:-


The concept of dynamic memory allocation in c language enables the C
programmer to allocate memoryat runtime.
Dynamic memory allocation in c language is possible by 4functions of stdlib.h header
file.
1. malloc()
2. calloc()
3. realloc()
4. free()
Before learning above functions, let's understand the differencebetween static memory
allocation and dynamic memory allocation.

static memory allocation dynamic memory allocation

memory is allocated at
compiletime. memory is allocated at run
time.

memory can't be increased memory can be increased


whileexecuting program. whileexecuting program.

used in array. used in linked list.

Now let's have a quick look at the methods used for dynamic memoryallocation.

malloc() allocates single block of requested memory.


calloc() allocates multiple block of requested memory.

reallocates the memory occupied by malloc() or


realloc() calloc()functions.

free() frees the dynamically allocated memory.

Array of Pointers:-
In computer programming, an array of pointers is an indexed set of variables in which the
variables are pointers (a referenceto a location in memory).
Pointers are an important tool in computer science forcreating, using, and
destroying all types of data structures.
An array of pointers is useful for the same reason that allarrays are useful: it allows
you to numerically index a large set of variables.
Below is an array of pointers in C that sets each pointer inone array to point to an
integer in another and then print the values of the integers by dereferencing the
pointers.

POINTERS WITH ARRAYS:-

When an array is declared, elements of array are stored in contiguous locations. The
address of the first element of an array is called its base address.

Consider the array


2000 2002 2004 2006 2008

a[0] a[1] a[2] a[3] a[4]

The name of the array is called its base address.i.e., a and k& a[20] are equal

Now both a and a[0] points to location 2000. If we declare p as an integer pointer, then we can
make the pointer P to point to the array a by followingassignment.
P = a;
We can access every value of array a by moving P from one element to another.i.e., P
points to 0th element
P+1 points to 1st element
P+2 points to 2nd element
P+3 points to 3rd element P
+4 points to 4th element
Let's understand the dangling pointer through some C programs. Using
free() function to de-allocate the memory.
1. #include <stdio.h>
2. int main()
3. {
4. int *ptr=(int *)malloc(sizeof(int));
5. int a=560;
6. ptr=&a;
7. free(ptr);
8. return 0;
9. }
In the above code, we have created two variables, i.e., *ptr and a where 'ptr' is a pointer and 'a' is
a integer variable. The *ptr is a pointer variable which is created with the help of
malloc() function. As we know that malloc() function returns void, so we use int * to convert void
pointer into int pointer.
e statement int *ptr=(int *)malloc(sizeof(int)); will allocate the memory with 4 bytes shown
in the below image:

The statement free(ptr) de-allocates the memory as shown in the below image with a cross sign,
and 'ptr' pointer becomes dangling as it is pointing to the de-allocated memory.

If we assign the NULL value to the 'ptr', then 'ptr' will not point to the deleted memory.
Therefore, we can say that ptr is not a dangling pointer, as shown in the below image:

Variable goes out of the scope

When the variable goes out of the scope then the pointer pointing to the variable becomes a
dangling pointer.

Command Line Arguments in C

The arguments passed from command line are called command line arguments. These
arguments are handled by main() function.

To support command line argument, you need to change the structure of main() function as given
below.

1. int main(int argc, char *argv[] )


Here, argc counts the number of arguments. It counts the file name as the first argument.The
argv[] contains the total number of arguments. The first argument is the file name always.

Example

Let's see the example of command line arguments where we are passing one argument with file
name.

#include <stdio.h>

void main(int argc, char *argv[] ) {

printf("Program name is: %s\n", argv[0]);

if(argc < 2){

printf("No argument passed through command line.\n");

else{

printf("First argument is: %s\n", argv[1]);

Output:

Programnameis:program First

argument is: hello

If you pass many arguments, it will print only one.


1. ./program hello c how r u

Output:

Programnameis:program

Firstargumentis:hello

Dynamic Memory Allocation


Some programming languages allocate memory to the variables at the compilation time. This is
called static memory allocation. This requires that all the variables used in the program be
completely defined in the source program. For variables like arrays the programmer has to estimate
the requirement which may result in shortage or wastage of memory.

C language provides facilities to allocate memory to variables during the execution time and also to
release memory when no longer required. This is called dynamic memory allocation.

In C language there are four functions used with dynamic memory management. – malloc(), calloc()
and realloc() for allocation and free() to return memory. These functions are defined in the header file
<stdlib.h>.

A conceptual view of memory is shown below though the actual implementations may vary slightly.

main() must be in memory all the times. Called functions may be present in the memory only
when active or at all times (depending on the implementation)
Local variables for a function available only when the function is active and are managed from the
stack.
Dynamic memory allocation is done using the heap.

malloc()
· Allocates a block of memory as specified in its parameters.
· Returns a pointer to the first byte of the allocated memory.
· The allocated memory is not initialized (contains garbage).

Prototype:
void * malloc(size_t size);

· returns a pointer to size bytes of memory block else returns NULL.


· size is usually specified using sizeof() function.

Usage:
ptr = malloc (sizeof(data_type));

It is better to make the pointer to be of a specific type using typecasting as below: ptr =

(data_type *) malloc (sizeof(data_type));

E.g.:
int *p;
p = (int *) malloc(sizeof(int)); // allocates two bytes of memory to store an integer

calloc()

· primarily used to allocate memory to arrays


· Allocates contiguous block of memory for the array
· Returns a pointer to the first byte of the allocated memory.
· The allocated memory is initialized (memory is cleared).

Prototype:
void *calloc(size_t element_count, size_t element_size);
· returns a pointer to size bytes of memory block else returns NULL.
· size is usually specified using sizeof() function.

Usage:
ptr = calloc (integer value, sizeof(data_type));

It is better to make the pointer to be of a specific type using typecasting as below: ptr =

(data_type *) calloc (count, sizeof(data_type));

E.g.:
int *p;
p = (int *) calloc(200, sizeof(int)); // allocates memory for 200 integers

realloc()
· changes the size of the previously allocated memory block.
· Can be highly inefficient and hence should be used carefully.
· Prototype:
void *realloc(void *ptr, size_t newsize);

E.g.:
int *p;
p = (int *) malloc(sizeof(int)); //initially only 2 bytes allocated
p = (int *) realloc(p, 15 * sizeof(int)); // reallocates memory for 15 integers

free()
· When memory allocated by malloc(), calloc() or realloc() are no longer needed, it can be freed.
· Prototype:
void free(void *ptr);

E.g.:
free(ptr);
Note: Any pointer to the freed memory is not destroyed and hence it is better to set
it to NULL and avoid errors.
Programming example:

//Write a program that uses a table of integers whose size will be specified interactively at run
time.
#include<stdio.h>
#include<stdlib.h>
#include<conio.h> void
main()
{
int *p, *table; int size;
clrscr();
printf("\nWhat is the size of the table");
scanf("%d",&size);
table = (int *)malloc(size * size(int)); // allocates memory for specified numbers using malloc
printf("Enter %d numbers", size); for(p=table;
p<table + size; p++)
scanf("%d",p);
for(p=table; p<table + size; p++)
printf("%d is stored at address %u",*p, p); getch();
}
//Same program using calloc function
#include<stdio.h>
#include<stdlib.h>
#include<conio.h> void
main()
{
int *p, *table; int size;
clrscr();
printf("\nWhat is the size of the table");
scanf("%d",&size);
table = (int *)calloc(size, size(int)); // allocates memory for specified numbers using calloc
printf("Enter %d numbers", size); for(p=table;
p<table + size; p++)
scanf("%d",p);
for(p=table; p<table + size; p++)
printf("%d is stored at address %u",*p, p); getch();
}
What is a structure?
A structure is a user defined data type in C and C++ language. It creates a data type that can be used
to group items of possibly different types into a single type.

· How to create a structure?


‘struct’ keyword is used to create a structure. An example is given below

Syntax: struct<structure_name>
{
data_type variable1;
data_type variable2;
data_type variable3;
----
----
};
Example:struct address
{
char name[50]; char city[50]; char state[20]; int pin;
};
· How to declare structure variables?
A structure variable can either be declared with structure declaration or as a separate declaration like basic
types.
// Type-1Structure variable declaration.
struct Point
{
int x, y;
} p1; // The variable p1 is declared with 'Point'

// Type-2 Structure variable declaration.


struct Point
{
int x, y;
};

void main()
{
struct Point p1; // The variable p1 is declared like a normal variable
}How to initialize structure members?
Structure members cannot be initialized with declaration.
For example, the following C program used to show WRONG initialization

struct Point
{
int x = 0; // COMPILER ERROR: cannot initialize members here int y =
0; // COMPILER ERROR: cannot initialize members here
};
The reason for above error is simple, when a datatype is declared; no memory is allocated for it. Memory is
allocated only when variables are created.

Structure members can be initialized using curly braces ‘{}’. For


example, following is a CORRECT initialization.

struct Point
{
int x, y;
};

void main()
{
struct Point p1 = {0, 1};
}

· How to access structure elements?


Structure members are accessed using dot (.) operator.
94
#include<stdio.h>
#include<conio.h>
structTEST
{
int x, y;
};

void main()
{
structTESTt1 = {0, 1};

// Accessing members of TEST t1 t1.x = 20;


printf ("x = %d, y = %d", t1.x, t1.y); getch();
}
· What is an array of structures?
Structure is collection of different data type. An object of structure represents a single record in memory, but
if we want more than one record of structure type, we have to create an array of structure.Like other
primitive data types, we can create an array of structures.

#include<stdio.h> #include<conio.h>

struct Point // Structure declaration


{
int x, y;
};

void main()
{
struct Point arr[10]; // Create an array of structures

arr[0].x = 10; // Access array members arr[0].y


= 20;

printf("%d %d", arr[0].x, arr[0].y); getch();


}

· Limitations of C Structures
In C language, Structures provide a method for packing together data of different types. A Structure is a
helpful tool to handle a group of logically related data items. However, C structures have some limitations.

a. The C structure does not allow the struct data type to be treated like built-in data types.We cannot use
operators like +,- etc. on Structure variables.
b. No Data Hiding:C Structures do not permit data hiding. Structure members can be accessed by
any function, anywhere in the scope of the Structure.
c. Functions inside Structure: C structures do not permit functions inside Structure.
d. Static Members: C Structures cannot have static members inside their body.
e. Access Modifiers: C Programming language do not support access modifiers. So they cannot be used
95
in C Structures.

Accessing Structure Members in C:

1. Array elements are accessed using the Subscript variable, Similarly Structure members are
accessed using dot [.] operator.
2. (.) is called as “Structure member Operator”.
3. Use this Operator in between “Structure name” & “member name”

Example:
#include<stdio.h>
#include<conio.h>

structVehicle
{
intwheels;
charvname[20];
charcolor[10];
}v1={4,"Maruti800","White"};

voidmain()
{
printf("VehicleNoofWheels:%d",v1.wheels);
printf("Vehicle Name : %s",v1.vname);
printf("Vehicle Color

: %s",v1.color);getch();
}

Structure with in Structure:Nested Structure

· Structure written inside another structure is called as nesting of two structures.


· Nested Structures are allowed in C Programming Language.
· We can write one Structure inside another structure as member of another structure.

I-Way of declaration of nested structure:structdate


{
int date;
int month;
int year;
};
96
struct Employee
{
char ename[20];
int ssn;
float salary;
struct datedoj;
}emp1;
Way of Accessing Elements of Nested Structure:
1. Structure members are accessed using dot operator.
2. ‘date‘structure is nested within Employee Structure.
3. Members of the ‘date‘ can be accessed using ’employee’
4. emp1 & doj are two structure names (Variables)

Explanation of Nested Structure :


AccessingMonth Field:emp1.doj.month
AccessingdayField:emp1.doj.day Accessing
year Field:emp1.doj.year

II-Way of declaration of embedded structures:

structEmployee
{
charename[20];
intssn;floatsalary;str
uctdate
{
intdate;intmonth;int
year;
}doj;
}emp1;

Accessing Nested Members :


AccessingMonthField:emp1.doj.month Accessing day
Field:emp1.doj.day
AccessingyearField:emp1.doj.year
Example:
#include<stdio.h>#include<c
onio.h>
97
structEmployee
{
charename[20];
intssn;floatsalary;str
uctdate
{
intdate;intmonth;int
year;
}doj;
}emp={"Pritesh",1000,1000.50,{22,6,1990}};

Voidmain()
{
printf("\nEmployeeName:%s",emp.ename);
printf("\nEmployee SSN : %d",emp.ssn);
printf("\nEmployee Salary : %f",emp.salary);
printf("\nEmployee DOJ : %d/%d/%d", \
emp.doj.date,emp.doj.month,emp.doj.year);

getch();
}

Pointer to structure : Pointer which stores address of structure is called as “Pointer to Structure“.
Explanation :
1. sptr is pointer to structure address.
2. -> and (*). both represent the same.
3. These operators are used to access data member of structure by using structure’s pointer.
Program :
#include<stdio.h>

struct team {
char *name;
int members;
char captain[20];
}t1={"India",11,"Dhoni"} ,*sptr=&t1;

int main()
{

printf("\nTeam : %s",(*sptr).name);
printf("\nMemebers:%d",sptr->members);
98
printf("\nCaptain : %s",(*sptr).captain);

return0;
}
Passing Structure to Function in C Programming
1. Structure can be passed to function as a Parameter.
2. function can also Structure as return type.
3. Structure can be passed as follow

Example:

#include<stdio.h>
#include<conio.h>
//
struct Example
{
int num1;
int num2;
}s[3];
//
void accept(struct Example*sptr)
{
printf("\nEnter num1: ");
scanf("%d",&sptr->num1);
printf("\nEnter num2 :");
scanf("%d",&sptr->num2);
}
//
void print(struct Example*sptr)
{
printf("\nNum1:%d",sptr->num1);
printf("\nNum2:%d",sptr->num2);
}
//
void main()
{
int i;
clrscr();
for(i=0;i<3;i++)
accept(&s[i]);

for(i=0;i<3;i++) print(&s[i]);

getch();
99
}

Accessing Element in Structure Array

1. Array of Structure can be accessed using dot [.] operator.


2. Here Records of 3 Employee are Stored.
3. ‘for loop’ is used to Enter the Record of first Employee.
4. Similarly ‘for Loop’ is used to Display Record.

Example:
#include<stdio.h>
#include<conio.h>

struct Employee
{
int ssn;
char ename[20];
char dept[20];
}emp[3];

//
void main()
{
inti,sum;

//Enter the Employee Details


for(i=0;i<3;i++)
{
printf("nEnter the Employee Details:");
scanf("%d%s%s",&emp[i].ssn,emp[i].ename,emp[i].dept);
}
//Print Employee Details
for(i=0;i<3;i++)
{
printf("nEmployee SSN:%d",emp[i].ssn);
printf("nEmployeeName:%d",emp[i].ename);
printf("nEmployee Dept: %d",emp[i].dept);
}
getch();
}

Unions
· A union is declared and used in the same ways that a structure.
· Unions are defined and declared in the same fashion as structures.
100
· In unions, all the members share the space which is according to the space requirement of the largest
member.
· The union can hold only one value at a time.
· A union can be initialized on its declaration.
· Because only one member can be used at a time, only one can be initialized.
· To avoid confusion, only the first member of the union can be initialized.
Defining of Union
· A union has to defined, before it can be used.
· The syntax of defining a structure is union
<union_name>
{
<data_type> <variable_name>;
<data_type> <variable_name>;
………….
<data_type> <variable_name>;
};
Example
To define a simple union of a char variable and an integer variable union
shared
{ char c;
int i;
};
This union, shared, can be used to create instances of a union that can hold either a character
value(c) or an integer value( i ).
Union Data Type
· A union is a user defined data type like structure.
· The union groups logically related variables into a single unit.
· The union data type allocates the space equal to space needed to hold the largest data member of
union.
· The union allows different types of variable to share same space in memory.
· There is no other difference between structure and union than internal difference.
· The method to declare, use and access the union is same as structure.

Accessing Union Members


· Individual union members can be used in the same way that structure members can be used­
­by using the member dot operator (.).
· Only one union member should be accessed at a time, as different variable share same space in memory.

Example
union shared
{ char c; int i;
};

shared.c =’a’; shared.d=1;


101
In this case, value assignment to member variable (d) overwrites the member variable(c).

Difference between Structures & Union


· The memory occupied by structure variable is the sum of sizes of all the members but memory
occupied by union variable is equal to space hold by the largest data member of a union.
· In the structure all the members can be accessed at any point of time but in union only one of union
member can be accessed at any given time.

Example
#include<stdio.h>
union job
{ char name[32]; float salary;
int worker_no;
} u;
struct job1
{ char name[32]; float salary;
int worker_no;
} s;
void main( )
{
printf("size of union = %d", sizeof(u));
printf("\nsize of structure = %d", sizeof(s));
}
output
size of union = 32
size of structure = 40
Difference between Structure and Union

Structure Union
1. It can be defined using struct keyword. It can be defined using a union keyword.
2. Every member within structure is assigned a In union, a memory location is shared by all the data
unique memory location. members.
3. Changing the value of one data member will not Changing the value of one data member will change the
affect other data members in structure. value of other data members in union.

4. It allows initializing several members at once. It allows initializing only the first member of union.

5. The total size of the structure is the sum of the size The total size of the union is the size of the largest data
of every data member. member.
6. It is used for storing various data types. It is used for storing one of the many data types that are
available.
7. It reserves space for each and every member It reserves space for a member having the highest size.
separately. 102
8. Any member can be retrieve at a time. Only one member can be retrieve at a time.
9. It allows dynamic array as member. It does not allows dynamic array as member.

Nested Structure and Union


· A structure can have nested union as a member.
· A union can have a nested structure as a member.
· A union can also have a nested union as a member.

Example.

unionshared structshared
{charc; int {charc; int
i; i;
}; };

structA BC unionABC
{ intx; { intx;
unionsharedy; structsharedy;
}; };

103

You might also like